AI编程生活评测

Python笔记:文件IO操作

编程笔记 / 2020-08-04 / 2 min

读取文件

使用 open() 打开文件,文件不存在会抛出 IOError 错误。
try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()
文件读取完成一定要 close() ,为了保证在报错的时候也能 close() ,这里用了 finally 语句,更简洁的写法是用 with 语句,会自动关闭。
with open('/path/to/file', 'r') as f:
    print(f.read())
第二个参数 r 读取文本文件,如果要读取二进制文件使用 rb

读取大文件

很小的文件直接使用 read() 读取,大文件(超过1G)需要考虑使用分片或者单行读取或者迭代之类的。 readlines读取
with open(filename, 'rb') as f:
    for line in f.readlines():
        print(line.strip().decode())
read(size)分片读取 使用 read(chunk_size) 指定大小去分片读取文件。
with open(filePath, 'rb') as f:
    while True:
        chunk_data = f.read(chunk_size)
        if not chunk_data:
            break
        print(chunk_data.strip().decode())
迭代行
with open(filename, 'rb') as f:
    for line in f:
        print(line.strip().decode())
strip():去掉末尾换行 decode():将二进制转换成字符串

读取非utf-8编码

指定编码,比如 gbk
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore') # 忽略错误

写入文件

传入标识符 'w' 或者 'wb' 表示写文本文件或写二进制文件:
with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')
'w' 模式写入文件时,如果文件不存在会新建,如果文件已存在,会直接覆盖内容。

追加写入

传入 'a'append 模式写入。写入中文时,指定编码 utf8 防止乱码。
with open('/Users/michael/test.txt', 'a', encoding='utf8') as f:
    f.write('\n追加写入:Hello, world!')
  1. 周良粥凉 2020-08-14 · 20:20

    我觉得以后有 Python 问题可以请教你了,哈哈

    1. 行星带 2020-08-19 · 11:54

      Python我是初学者,可以相互交流的,期待向你学习