读取文件
使用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!')
Python笔记:文件IO操作
原文链接:https://beltxman.com/3201.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。
我觉得以后有 Python 问题可以请教你了,哈哈
Python我是初学者,可以相互交流的,期待向你学习