open | write | read
>>> with open('demo.txt' , 'wt') as f: #以文本(wt)形式写入操作
... f.write("hello guohai")
12
>>> with open('demo.txt' , 'rt') as f: #以文本(rt)形式读取操作
... data = f.read()
>>> data
'hello guohai'
>>> with open('demo.txt' , 'at') as f: #以文本(at)形式追加操作
... f.write('hello zeopean')
13
>>> with open('demo.txt' , 'rt') as f:
... data = f.read()
>>> data
'hello guohaihello zeopean'
-- print 输出到文件中
with open('d:/work/test.txt', 'wt') as f:
print('Hello World!', file=f)
-- 二进制读写
如果你想从二进制模式的文件中读取或写入文本数据,必须确保要进行解码和编码
操作。比如:
1 with open('somefile.bin', 'rb') as f:2
3 data = f.read(16)4
5 text = data.decode('utf-8')6
7 with open('somefile.bin', 'wb') as f:8
9 text = 'Hello World'
10
11 f.write(text.encode('utf-8'))12
13
-- 判断文件是否存在
>>> importos>>> if not os.path.exists('somefile'):
... with open('somefile', 'wt') as f:
... f.write('Hello\n')
...else:
...print('File already exists!')
...
File already exists!
StringIO | BytesIO
1 --StringIO2
3 >>> s =io.StringIO()4
5 >>> s.write('Hello World\n')6
7 12
8
9 >>> print('This is a test', file=s)10
11 15
12
13 >>>s.getvalue()14
15 'Hello World\nThis is a test\n'
16
17 >>>
18
19 >>> s = io.StringIO('Hello\nWorld\n')20
21 >>> s.read(4)22
23 'Hell'
24
25 >>>s.read()26
27 'o\nWorld\n'
28
29 >>>
30
31
32
33 --BytesIO34
35 >>> s =io.BytesIO()36
37 >>> s.write(b'binary data')38
39 >>>s.getvalue()40
41 b'binary data'
42
43 >>>
readinto | bytearray | memoryview
1 record_size = 32
2
3 buf =bytearray(record_size)4
5 with open('somefile', 'rb') as f:6
7 whileTrue:8
9 n =f.readinto(buf)10
11 if n