Python基础-IO操作

关于IO的相关操作,主要操作文件夹 、文件 、路径等内容

pyth相关操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
from pathlib import *

pp = PurePath('setup.py')
print(type(pp))
pp = PurePath('crazy', 'some/path', 'info')
print(pp)
pp = PurePath(Path('crazy'), Path('hello'))
print(pp)
pp = PurePosixPath('crazy', 'some/path', 'info')
print(pp)
pp = PurePath()
print(pp)
pp = PurePosixPath('/ect', '/usr', 'lib64')
print(pp)
print(PurePosixPath('info') == PurePosixPath('INFO'))
print(PureWindowsPath('info') == PureWindowsPath('INFO'))
pp = PureWindowsPath('hello', 'nihao')
print(pp / 'world' / 'print')
print(str(pp))
pp = PurePosixPath('hello', 'nihao')
print(pp / 'world' / 'print')
print(str(pp))
print('===========path========')
p = Path('.')
for e in p.iterdir():
print(e)

p = Path('../')
for x in p.glob('**/*.py'):
print(x)

# p=Path(r'E:\python\python2.7')
# for x in p.glob("**/*.py"):
# print(x)
p = Path('test.txt')

result = p.write_text("""
有一个美丽的世界
它在远方等我
那里有天真的孩子
还有姑娘的酒窝""", encoding='UTF-8')
print(result)

content = p.read_text(encoding='UTF-8')
print(content)

b = p.read_bytes()
print(b)

print("==========os.path==========")
import os
import time

print(os.path.abspath('test.txt'))
print(os.path.commonprefix(['/usr/lib', '/usr/local/lib']))
print(os.path.commonpath(['/usr/lib', '/usr/local/lib']))
print(os.path.dirname('/usr/carzy/book/test.txt'))
print(os.path.exists('/usr/carzy/book/test.txt'))
print(time.ctime(os.path.getctime('test.txt')))
print(time.ctime(os.path.getmtime('test.txt')))
print(time.ctime(os.path.getatime('test.txt')))
print(os.path.isfile('test.txt'))
print(os.path.isdir('test.txt'))
print(os.path.getsize('test.txt'))
print(os.path.samefile('test.txt', './test.txt'))
print('=============fnmatch=================')
import fnmatch
for file in Path('.').iterdir():
if(fnmatch.fnmatch(file, '*t.txt')):
print(file)
names = ['a.py', 'b.py', 'c.py', 'd.py']
sub = fnmatch.filter(names, '[a-c].py')
print(sub)

print("============打开文件open()===============")
f = open('hello.txt')
print(f.encoding)
print(f.name)
print(f.mode)
print(f.closed)

f.close()

print("==============读取文件====================")

f = open('test.txt', 'r', True, encoding='UTF-8')
while True:
ch = f.read(1)
if not ch:
break
print(ch, end=' ')
f.close()

f = open('test.txt', 'r', True, encoding='UTF-8')
print(f.read())
f.close()

# 二进制读取
f = open('hello.txt', 'rb', True,)
print(f.read().decode('utf-8'))
f.close()

f = open('test.txt', 'r', True, encoding='utf-8')
while True:
line = f.readline()
if not line:
break
print(line, end=' ')
f.close()
print('')
print('-----------------lines----------------------')
f = open('test.txt', 'r', True, encoding='utf-8')
for l in f.readlines():
print(l, end=' ')
f.close()

import fileinput
print('==================fileinput====================')
for line in fileinput.input(files=('file/a.txt', 'file/b.txt')):
print(fileinput.filename(), fileinput.filelineno(), line, end='')
fileinput.close()

f = open('test.txt', 'r', True, encoding='utf-8')
for line in f:
print(line, end=' ')
# print(list(open('test.txt','r',True,encoding='utf-8')))
f.close()
print(' ')

import sys
for line in sys.stdin:
print("用户输入:", line)

读写文件相关操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import fileinput

with open('test.txt', 'r', True, encoding='utf-8') as f:
for line in f:
print(line)

with fileinput.input(files=('file/a.txt', 'file/b.txt')) as f:
for line in f:
print(line)


class FKResource:

def __init__(self, tag):
self.tag = tag
print("初始化 %s" % tag)

def __enter__(self):
print('__enter__: %s' % self.tag)
return 'fkit'

def __exit__(self, exc_type, exc_value, exc_traceback):
print('__exit__:%s' % self.tag)
if exc_traceback is None:
print("无异常关闭资源")
else:
print("异常关闭资源")
return False


try:
with FKResource('丽丽') as dr:
print(dr)
print('with 无异常')
print("---------------------------")
with FKResource('天天'):
print('wiht 异常之前')
raise Exception
print('with 有异常')
except Exception as e:
pass

print('-------------linecache----------')
import linecache
import random

print(linecache.getline(random.__file__, 3))
print(linecache.getline('read_write_file.py', 8))
print(linecache.getline('test.txt', 3))

print('------------write---------------')

with open('my_test.txt', 'rb') as f:
print(f.tell())
f.seek(3)
print(f.tell())
print(f.read(1))
print(f.tell())
f.seek(5)
print(f.tell())
f.seek(5, 1)
print(f.tell())
f.seek(-10, 2)
print(f.tell())
print(f.read(1))
print(f.tell())

import os
f = open('x.txt', 'w+', encoding='utf-8')
f.write('我爱Python' + os.linesep)
f.writelines(('牢记使命' + os.linesep,
'不忘初心' + os.linesep,
'艰苦奋斗' + os.linesep,
'永不放弃' + os.linesep))
f.close()

f = open('y.txt', 'wb+')
f.write(('我爱Python' + os.linesep).encode('utf-8'))
f.writelines((('牢记使命' + os.linesep).encode('utf-8'),
('不忘初心' + os.linesep).encode('utf-8'),
('艰苦奋斗' + os.linesep).encode('utf-8'),
('永不放弃' + os.linesep).encode('utf-8')))
f.close()

f = open('z.txt', 'a+', encoding='utf-8')
f.write('我爱Python' + os.linesep)
f.writelines(('牢记使命' + os.linesep,
'不忘初心' + os.linesep,
'艰苦奋斗' + os.linesep,
'永不放弃' + os.linesep))
f.close()

os 模块相关操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import stat

print(os.getcwd())
os.chdir('../../crazy-py')
print(os.getcwd())
os.chdir('11io')
print(os.listdir())
path = 'my_dir'
# os.mkdir(path)
path = 'abc/d/e/f'
# os.makedirs(path)
# os.rmdir('my_dir')
# os.removedirs('abc/d/e/f')
# os.rename('my_dir', 'you_dir')
# os.renames('abc/d/e/f', 'q/x/y/z')
ret = os.access('.', os.F_OK | os.R_OK | os.W_OK | os.X_OK)
print(ret)
ret = os.access('os_operate.py', os.F_OK | os.R_OK | os.W_OK)
print(ret)
os.chmod('read.txt', stat.S_IREAD)
ret = os.access('read.txt', os.W_OK)
print(ret)

f = os.open('abc.txt', os.O_RDWR | os.O_CREAT)
len1 = os.write(f, '好好学习\n'.encode('utf-8'))
len2 = os.write(f, '天天向上\n'.encode('utf-8'))
os.lseek(f, 0, os.SEEK_SET)
data = os.read(f, len1 + len2)
print(data)
print(data.decode('utf-8'))
os.close(f)

import tempfile
fp = tempfile.TemporaryFile()
print(fp.name)
fp.write('你是最好的风景,'.encode('utf-8'))
fp.write('迷人又危险'.encode('utf-8'))
fp.seek(0)
print(fp.read().decode('utf-8'))
fp.close()

with tempfile.TemporaryFile() as fp:
fp.write(b'i love you so much')
fp.seek(0)
print(fp.read())

with tempfile.TemporaryDirectory() as tmpdirname:
print('临时目录', tmpdirname)