Python 文件基本操作(读写)汇总
一、文件操作核心概念
- 操作流程:打开文件 → 读写文件 → 关闭文件(必须关闭,否则占用资源)
- 核心函数:
open()(打开)、read()/readline()/readlines()(读)、write()/writelines()(写)、close()(关闭) - 编码规范:必须指定编码
encoding='utf-8',避免中文乱码/报错 - 最佳写法:
with语句(自动关闭文件,无需手动写close(),推荐优先用)
二、open()函数完整语法
# 语法open(文件路径,模式,encoding='utf-8')# 参数说明# 1. 文件路径:相对路径(如 hello.txt)或绝对路径(如 G:/python/hello.txt)# 2. 模式:决定文件是读、写、追加等(核心)# 3. encoding:固定写 utf-8,解决中文乱码常用文件模式(必记)
| 模式 | 作用 | 注意事项 |
|---|---|---|
r | 只读(默认) | 文件必须存在,不存在报错 |
w | 只写 | 文件不存在则创建;存在则清空原有内容 |
a | 追加写 | 文件不存在则创建;存在则在末尾添加内容 |
r+ | 读写 | 文件必须存在,可同时读+写 |
wb | 二进制写(图片/视频) | 无需指定编码 |
rb | 二进制读(图片/视频) | 无需指定编码 |
三、文件读取操作(4种常用方法,含 readline)
1. 一次性读取全部内容(小文件用)
# with 自动关闭文件(推荐)withopen('hello.txt','r',encoding='utf-8')asf:content=f.read()# 读取所有文本print(content)# 打印文件全部内容2. 逐行读取(readline(),一次读一行)
withopen('hello.txt','r',encoding='utf-8')asf:line1=f.readline()# 读取第一行line2=f.readline()# 读取第二行print(line1.strip())# 去除换行符/空格print(line2.strip())3. 读取所有行到列表(readlines())
withopen('hello.txt','r',encoding='utf-8')asf:lines=f.readlines()# 返回列表:['第一行\n', '第二行\n', ...]print(lines)4. 逐行迭代遍历(大文件用,最省内存)
withopen('hello.txt','r',encoding='utf-8')asf:forlineinf:# 逐行读取,不占用大量内存print(line.strip())四、文件写入操作
1. 覆盖写入(w模式)
原有内容会全部清空,写入新内容
withopen('hello.txt','w',encoding='utf-8')asf:f.write('第一行内容\n')# \n 表示换行f.write('第二行内容\n')f.write('Python文件操作')2. 追加写入(a模式)
不清空原有内容,在文件末尾添加新内容
withopen('hello.txt','a',encoding='utf-8')asf:f.write('\n追加的第一行\n')f.write('追加的第二行')3. 批量写入多行(writelines())
withopen('hello.txt','w',encoding='utf-8')asf:lines=['第一行\n','第二行\n','第三行\n']f.writelines(lines)# 批量写入列表中的所有行五、文件读写结合(r+模式)
withopen('hello.txt','r+',encoding='utf-8')asf:content=f.read()# 先读f.write('\n新增内容')# 再写(写入到文件末尾)print("读取内容:",content)六、二进制文件操作(图片/视频/音频)
无需指定编码,模式用rb/wb
# 复制图片(二进制读 + 二进制写)withopen('test.jpg','rb')asf1:data=f1.read()# 读取二进制数据withopen('test_copy.jpg','wb')asf2:f2.write(data)# 写入二进制数据七、读取方法对比表
| 方法 | 功能 | 适用场景 |
|---|---|---|
read() | 一次性读取全部内容 | 小文件 |
readline() | 一次读取一行内容 | 需要逐行处理、控制读取进度 |
readlines() | 读取所有行,返回列表 | 需要对所有行进行列表操作 |
for line in f | 逐行迭代读取 | 大文件,节省内存 |
八、常见错误及解决方法
1. 编码报错
UnicodeDecodeError: 'gbk' codec can't decode byte✅ 解决:打开文件必须加encoding='utf-8'
2. 文件不存在报错
FileNotFoundError✅ 解决:用w/a模式会自动创建文件,r模式需确保文件存在
3. 写入后内容消失
✅ 原因:用了w模式(覆盖写入),想保留内容用a追加模式
九、完整代码示例
# 1. 写入文件withopen('test.txt','w',encoding='utf-8')asf:f.write('Python 文件操作\n')f.write('读写汇总\n')# 2. 读取文件withopen('test.txt','r',encoding='utf-8')asf:print(f.read())# 3. 逐行读取withopen('test.txt','r',encoding='utf-8')asf:print("第一行:",f.readline().strip())# 4. 追加内容withopen('test.txt','a',encoding='utf-8')asf:f.write('追加内容:学习愉快!')# 5. 再次读取验证withopen('test.txt','r',encoding='utf-8')asf:print("\n最终内容:")print(f.read())十、核心总结
- 永远用
with open():自动关闭文件,安全简洁 - 永远加
encoding='utf-8':解决中文乱码/编码报错 - 读文件用
r,写文件用w,追加用a - 小文件
read(),单行用readline(),全部行用readlines(),大文件逐行遍历 - 二进制文件(图片/视频)用
rb/wb,不加编码