Python 中读取、写入文件,都可以通过方法 open() 实现,该方法用于打开一个文件,然后返回文件对象,如果文件不存在或者无法打开,会报错 OSError。
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数说明:
file:必需,文件路径,相对或者绝对路径皆可;
mode:可选,文件打开的模式
buffering:设置缓冲
encoding:一般采用 utf8
errors:报错级别
newline:区分换行符
closefd:传入的 file 参数类型
操作模式 | 具体含义 |
---|---|
r | 读取(默认文件打开模式) |
w | 写入(会截断前面的内容) |
x | 写入,如果文件已经存在会产生异常 |
a | 追加,将内容写入到已有文件末尾 |
b | 二进制模式 |
t | 文本模式(默认) |
+ | 更新(既可以读又可以写) |
对于 open 方法返回的 file 文件对象,它常用函数有:
close():关闭文件
flush():将内部缓冲区数据立刻写入文件
read([size]):从文件读取指定的字节数,如果没有或者是负数值,则读取所有
readline():读取整行,包含换行符 \n 字符
readlines([sizeint]):读取所有行并返回列表,若给定 sizeint>0,返回总和大约为 sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。
write(str):将字符串写入文件,返回的是写入字符的长度
writelines(sequence):向文件写入一个序列字符串列表,如果需要换行,需要自己添加每行的换行符
seek(offset[, whence]):设置文件当前位置
tell():返回文件当前位置。
truncate([size]:从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后后面的所有字符被删除,其中 Windows 系统下的换行代表 2个字符大小。
读取文本文件
读取文件将采用操作系统默认的编码,通常如果文件内容不带有中文,可以省去encoding,如果带有中文内容,则必须指定 encoding=‘utf8’ 才能正常打开文件
# 方法1
f = open('test.txt', 'r')
print(f.read())
f.close()
这种方法存在问题,如果忘记调用 close 方法关闭文件,会出现错误。
因此推荐使用上下文语法,通过 with 关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源。
此外,读取文件内容,可以直接调用 read() 方法,也可以采用 for-in 循环读取:
# 方法2
with open('test.txt', 'r') as fr:
print(fr.read())
# 方法3 读取文件也可以采用 for-in 循环逐行读取
with open('test.txt', 'r') as fr:
for line in fr:
print(line.strip())
异常处理
异常处理,在出现异常后,是可以继续执行后续的代码(try-exception 后面的语句),即不会终止程序的执行
抛出异常
如果希望发生异常就终止程序运行,可以采用 raise 关键字
try:
with open(file_name, 'r', encoding='utf-8') as f:
file_contents = f.read()
except Exception as e:
print(e)
raise
写入文件
写入文件,只需要设置文件打开模式是写入模型,即 w
def save_to_file(input_file, outputfile, write_mode='w'):
file_contents = read_file(input_file)
try:
with open(outputfile, write_mode, encoding='utf-8') as fw:
fw.write(file_contents)
except IOError as ioerror:
print(ioerror)
print('写入文件出错')
input_file = 'test.txt'
output_file= 'new_test.txt'
save_to_file(input_file, output_file, write_mode='w')
读取二进制文件
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
def copy_image_file(input_image, output_image):
try:
with open(input_image, 'rb') as img1:
data = img1.read()
print(type(data))
with open(output_image, 'wb') as out:
out.write(data)
except FileNotFoundError as e:
print('指定的文件无法打开--{}'.format(input_image))
except IOError as e:
print('读写文件出现错误')
finally:
print('程序执行结束')
展示图片
%matplotlib inline
img = Image.open(input_image)
print(np.asarray(img, dtype=np.uint8).shape)
plt.imshow(img);
pathlib 模块
- 对于文件路径,最大的问题可能就是 Unix 系统和 Windows 系统采用的斜杠不同,前者是 / ,而后者是 \
from pathlib import Path
data_folder = Path('source_folder/python/')
file_path = data_folder / 'abc.txt'
print(file_path)
# 输出 source_folder\python\abc.txt
采用 pathlib 的方法,应该使用 /
斜杠,Path() 方法会自动根据当前系统修改斜杠,比如上述例子就更改为 Windows 的 \
- 读取文件内容不需要打开和关闭文件,如下所示,直接调用 read_text 方法即可读取内容
data_folder = Path('./')
file_path = data_folder / 'test.txt'
print(file_path.read_text())