文件读写
文件读写的本质是调用操作系统的system interface。
读文件
以读文件的模式打开一个文件对象
f = open('../module_test/hello.py', 'r') # 以读的方式打开一个文件
f.read() # 一次读取文件的全部内容到内存,用一个str对象表示
'print("in hello.py module")\n\nif __name__ == \'__main__\':\n print(\'in the __main__\')'
f.close() # 关闭文件
由于文件读写可能产生IOError
,可以使用try...except...finally
打开文件
try:
f = open('../module_test/hello2.py', 'r')
print(f.read())
except IOError as e:
print(e)
finally:
if f:
f.close()
[Errno 2] No such file or directory: '../module_test/hello2.py'
Python为了简洁,引入with
来自动帮我们调用close()
方法:
with open('../module_test/hello.py', 'r') as f:
print(f.read())
print("in hello.py module")
if __name__ == '__main__':
print('in the __main__')
一些其他的读文件方法:
read(size)
, 每次最多读取size
个字节的内容readline()
, 每次读取一行的内容readlines()
, 一次读取所有内容并按行返回list
。
file-like Object
像open()
函数返回的这种有个read()
方法的对象,在Python中统称为file-like Object
。除了file外,还可以是内存的字节流,网络流,自定义流等等。file-like Object
不要求从特定类继承,只要写个read()
方法就行。
StringIO
就是内存中创建的file-like Object, 常用作临时缓冲。
二进制文件读取以'rb'
模式打开文件,open('/filename', 'rb')
读取非UTF-8编码的文本文件,给open()
加上encoding=
参数即可。
f = open('/filename', 'r', encoding='gbk', errors='ignore')
写文件
调用open()
时,传入标识符'w'
或者'wb'
表示写文件, The mode can be 'r'
, 'w'
, 'x'
or 'a'
for reading (default), writing, exclusive creation or appending.
f = open('./test.txt', 'a')
f.write('Hello world')
f.close()
with open('./test.txt', 'w') as f:
f.write('Hello world!')
所有模式的定义可参考https://docs.python.org/3/library/functions.html#open
StringIO和BytesIO
数据读写不一定是在文件中,也可以内存中读写,StringIO和BytesIO是在内存中操作str
和bytes
的方法,使得和读写文件具有一致的接口
先创建一个StringIO,像文件一样写入
from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
hello world!
读取StringIO, 用str
初始化StringIO,然后像文件一样读取, BytesIO同理。
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
Hello!
Hi!
Goodbye!