One - One Code All

Blog Content

python文件读写with open

Python   2015-03-07 07:21:26
with open('/path/to/file', 'r') as f:
    print(f.read())


这和前面的try ... finally是一样的,但是代码更佳简洁,并且不必调用f.close()方法。

调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。

如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:

for line in f.readlines():
    print(line.strip()) # 把末尾的'\n'删掉
with open('/test.txt', 'w') as f:
    f.write('Hello, world!')


要写入特定编码的文本文件,请给open()函数传入encoding参数,将字符串自动转换成指定编码


上一篇:RuntimeWarning: invalid value encountered in true_divide
下一篇:nohup后台运行解决ignoring input and appending output

The minute you think of giving up, think of the reason why you held on so long.