Python 文件基本操作(读写)汇总

一、文件操作核心概念

  1. 操作流程:打开文件 → 读写文件 → 关闭文件(必须关闭,否则占用资源)
  2. 核心函数open()(打开)、read()/readline()/readlines()(读)、write()/writelines()(写)、close()(关闭)
  3. 编码规范必须指定编码 encoding='utf-8',避免中文乱码/报错
  4. 最佳写法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 自动关闭文件(推荐)
with open('hello.txt', 'r', encoding='utf-8') as f:
    content = f.read()  # 读取所有文本
    print(content)  # 打印文件全部内容

2. 逐行读取(readline(),一次读一行)

with open('hello.txt', 'r', encoding='utf-8') as f:
    line1 = f.readline()  # 读取第一行
    line2 = f.readline()  # 读取第二行
    print(line1.strip())  # 去除换行符/空格
    print(line2.strip())

3. 读取所有行到列表(readlines())

with open('hello.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()  # 返回列表:['第一行\n', '第二行\n', ...]
    print(lines)

4. 逐行迭代遍历(大文件用,最省内存)

with open('hello.txt', 'r', encoding='utf-8') as f:
    for line in f:  # 逐行读取,不占用大量内存
        print(line.strip())

四、文件写入操作

1. 覆盖写入(w 模式)

原有内容会全部清空,写入新内容

with open('hello.txt', 'w', encoding='utf-8') as f:
    f.write('第一行内容\n')  # \n 表示换行
    f.write('第二行内容\n')
    f.write('Python文件操作')

2. 追加写入(a 模式)

不清空原有内容,在文件末尾添加新内容

with open('hello.txt', 'a', encoding='utf-8') as f:
    f.write('\n追加的第一行\n')
    f.write('追加的第二行')

3. 批量写入多行(writelines())

with open('hello.txt', 'w', encoding='utf-8') as f:
    lines = ['第一行\n', '第二行\n', '第三行\n']
    f.writelines(lines)  # 批量写入列表中的所有行

五、文件读写结合(r+ 模式)

with open('hello.txt', 'r+', encoding='utf-8') as f:
    content = f.read()  # 先读
    f.write('\n新增内容')  # 再写(写入到文件末尾)
    print("读取内容:", content)

六、二进制文件操作(图片/视频/音频)

无需指定编码,模式用 rb/wb

# 复制图片(二进制读 + 二进制写)
with open('test.jpg', 'rb') as f1:
    data = f1.read()  # 读取二进制数据

with open('test_copy.jpg', 'wb') as f2:
    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. 写入文件
with open('test.txt', 'w', encoding='utf-8') as f:
    f.write('Python 文件操作\n')
    f.write('读写汇总\n')

# 2. 读取文件
with open('test.txt', 'r', encoding='utf-8') as f:
    print(f.read())

# 3. 逐行读取
with open('test.txt', 'r', encoding='utf-8') as f:
    print("第一行:", f.readline().strip())

# 4. 追加内容
with open('test.txt', 'a', encoding='utf-8') as f:
    f.write('追加内容:学习愉快!')

# 5. 再次读取验证
with open('test.txt', 'r', encoding='utf-8') as f:
    print("\n最终内容:")
    print(f.read())

十、核心总结

  1. 永远用 with open():自动关闭文件,安全简洁
  2. 永远加 encoding='utf-8':解决中文乱码/编码报错
  3. 读文件用 r,写文件用 w,追加用 a
  4. 小文件 read(),单行用 readline(),全部行用 readlines(),大文件逐行遍历
  5. 二进制文件(图片/视频)用 rb/wb,不加编码

更多推荐