Python文件读写

时间:2023-03-09 00:02:47
Python文件读写

读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的

文件打开模式

模式 意义
r 文本只读
w 文本只写
rb 二进制读
rw 二进制写

打开文件

选择一个模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符:

如果文件不存在,open()函数就会抛出一个IOError的错误,并且给出错误码和详细的信息告诉你文件不存在:

>>> f=open('data.txt', 'r')
Traceback (most recent call last):
File "<stdin>", line , in <module>
FileNotFoundError: [Errno ] No such file or directory: 'data.txt'

两种打开方式

# style 1
try:
f = open('data.txt', 'r')
print(f.read())
finally:
if f:
f.close() # style 2
# 和前面的try ... finally是一样的,但是代码更佳简洁,并且不必调用f.close()方法
with open('/path/to/file', 'r') as f:
print(f.read())

常用函数

f.read()返回文件所有内容

f.write(str) 写入参数必须是一个str

f.close() 关闭文件

# 文本方式读
# 1. 调用read(size)方法,每次最多读取size个字节的内容
# 2. 调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list[推荐]
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉 # 文本方式write
with open('data.txt','a') as f:
f.write("hello");

补充(其它打开方式):

# 读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件
f = open('data.txt', 'r', encoding='gbk') # 遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。
# 遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:
f = open('data.txt', 'r', encoding='gbk', errors='ignore')