IO在计算机中指的是Input/Output,也就是输入输出,在涉及到数据交换的地方,通常是磁盘、网络等,都需要用到IO接口。通常,程序完成IO操作会有Input和Output两个数据流。IO编程中,Stream是一个很重要的概念,Input Stream是指数据从外面(磁盘、网络)流进内存,Output Stream就是数据从内存流到外面。
- 文件读写
在进行文件操作时,容易产生IOError,所以示例代码都是用try…finally代码块。
- 读文件
try:
f=open(path,'r')
print(f.read())
finally:
if f:
f.close()
代码可以简化为:
with open(path,'r') as f:
print(f.read())
写文件
try: f=open(path,'w') f.write('File write') finally: if f: f.close()
同样,写文件可以简化为如下with代码:
with open(path,'w') as f: f.write('File Write Test')
- StringIO 和 BytesIO
StringIO
StringIO的作用是往内存中写入字符串,如下:from io import StringIO f=StringIO('Hello!\nHi!\nGoodBye!') while True: s=f.readline() if s=='': break print(s.strip())
输出结果:
Hello! Hi! GoodBye!
BytesIO
BytesIO可以操作二进制数据,如下:from io import BytesIO f=BytesIO() f.write('中文'.encode('utf-8')) print(f.getvalue())
输出结果:
b'\xe4\xb8\xad\xe6\x96\x87'