1, 读文件
举例:
>>> f = open('d://test.txt', 'r')>>>> f.read()'Hello, world!'>>>> f.close()
打开一个文件, 使用 open() 函数, 第一个参数是文件的路径, 第二个参数是读的意思. 如果路径错了会报错误:
>>> f = open('d://chen/test.txt', 'r')Traceback (most recent call last): File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory:'d://chen/test.txt'>>>
read(): 一次读取全部内容, 用一个 str 对象接收存进内存;
close(): 关闭文件, 每次使用完一定要关闭, 不关闭会占用系统资源.
open() 函数还有其他的参数:
'rb': 读取二进制文件
>>> f = open('/Users/michael/test.jpg', 'rb')
encoding: 读取指定编码文件
errors: 如果文件中有编码不对的, 如何处理. 以下代码是忽略 (ignore);
>>> f = open('d://test.txt', 'r',encoding='gbk', errors='ignore')
注意:
如果程序在运行中出错了, 那么最后执行的 close() 不能被调用, 则关闭不了文件一直占用系统资源, 而系统同一时间打开的文件是有限的. 此时, 我们可以使用 try...finally.
举例:
>>> try:... f = open('d://test.txt', 'r')... print(f.read())... finally:... if f:... f.close()...Hello World!>>>
但是如果每次都要扎样写, 未免有些繁琐, 所以, Python 提供了 with 语句来自动帮我们调用 close() 方法:
>>> with open('d://test.txt', 'r') as f:... print(f.read())...Hello World!>>>
效果和前面的 try...finally 一样, 且自动帮你调用 close(), 代码更简洁.
读取文件方式:
读取文件的时候, 除了 read(), 还有其他的方式, 如:
read(size): 一次读取 size 长度的字节, 下面代码是一次读取 1024 个字节.
>>> with open('d://test.txt', 'r') as f:... print(f.read(1024))...Hello World!
还可以用 readline() 一次读取一行, 用 readlines() 一次读取所有内容并按行返回 list
>>> with open('d://test.txt', 'r') as f:... for line in f.readlines():... print(line.strip()) #去掉每行后面的 \ n 换行符...Hello World!test
到底使用哪种读取方式比较好呢?
当文件很小的时候建议用 read() 一次读出所有, 当不知道文件大小的时候, 建议用 read(size) 一次一次的读取, 当读取配置文件的时候, 建议使用 readlines() 读取.
2, 写文件
举例:
>>> with open('d://test.txt', 'w') as f:... f.write('Hello world!')
写文件参数和读文件都是用 open() 函数,'w'是写的意思, 如果想指定写入编码, 可以再加一个 encoding 参数.
注意:
如果以'w'模式写入文件, 如果已经存在该文件, 则会被覆盖; 如果想追加在其后, 可以以'a'模式写入:
>>> with open('d://test.txt', 'a') as f:... f.write('Hello world!')
来源: http://www.92to.com/bangong/2018/08-17/34035313.html