文件的读写
读写文件是最常见的IO操作。
写文件
from datetime import datetime
with open('test.txt', 'w') as f:
f.write('今天是')
f.write(datetime.now().strftime('%Y-%m-%d'))
读文件
with open('test.txt', 'r') as f:
s = f.read()
print('open for read...')
print(s)
读取二进制文件
with open('test.txt', 'rb') as f:
s = f.read()
print('open as binary for read...')
print(s)
通过上面可以看出读写文件是非常简单的。
StringIO
除了在文件中读写,也可以在内存中进行读写。
StringIO 指的就是在内存中读写str 使用方法很简单,直接创建一个对象 StringIO,然后调用函数写入即可:
from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
运行结果:
hello world!
读取方式:
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
运行结果:
Hello!
Hi!
Goodbye!
ByteIO
写入方式:
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
输出结果:
b'\xe4\xb8\xad\xe6\x96\x87'
读取方式:
from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f.read())
输出结果:
b'\xe4\xb8\xad\xe6\x96\x87'
总结:
- 1、文件读写通过open()函数打开的文件对象完成的
- 2、使用with语句操作文件IO是个好习惯
- 3、StringIO 和 BytesIO 只要创建出对象,就可以进行内存的读写了