文件读写 #

一、打开文件 #

python
# open(文件名, 模式)
# 模式:'r'读, 'w'写, 'a'追加, 'x'创建
# 'b'二进制, 't'文本(默认), '+'读写

# 基本方式
f = open('file.txt', 'r')
content = f.read()
f.close()

# 推荐方式(自动关闭)
with open('file.txt', 'r') as f:
    content = f.read()

二、读取文件 #

python
# 读取全部
with open('file.txt', 'r') as f:
    content = f.read()

# 读取指定字符数
with open('file.txt', 'r') as f:
    chunk = f.read(100)  # 读取100个字符

# 读取一行
with open('file.txt', 'r') as f:
    line = f.readline()

# 读取所有行为列表
with open('file.txt', 'r') as f:
    lines = f.readlines()

# 逐行迭代(推荐)
with open('file.txt', 'r') as f:
    for line in f:
        print(line.strip())

三、写入文件 #

python
# 写入字符串
with open('file.txt', 'w') as f:
    f.write("Hello World\n")

# 写入多行
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('file.txt', 'w') as f:
    f.writelines(lines)

# 追加内容
with open('file.txt', 'a') as f:
    f.write("追加内容\n")

四、文件指针 #

python
with open('file.txt', 'r') as f:
    print(f.tell())      # 当前位置
    f.seek(10)           # 移动到位置10
    content = f.read(5)  # 读取5个字符
    f.seek(0)            # 回到开头

五、二进制文件 #

python
# 读取二进制
with open('image.png', 'rb') as f:
    data = f.read()

# 写入二进制
with open('copy.png', 'wb') as f:
    f.write(data)

# 复制文件
def copy_file(src, dst):
    with open(src, 'rb') as f1:
        with open(dst, 'wb') as f2:
            f2.write(f1.read())

六、编码 #

python
# 指定编码
with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# 处理编码错误
with open('file.txt', 'r', encoding='utf-8', errors='ignore') as f:
    content = f.read()

七、文件操作 #

python
import os

# 检查文件存在
os.path.exists('file.txt')

# 检查是文件还是目录
os.path.isfile('file.txt')
os.path.isdir('folder')

# 获取文件信息
os.path.getsize('file.txt')      # 文件大小
os.path.getmtime('file.txt')     # 修改时间

# 重命名
os.rename('old.txt', 'new.txt')

# 删除
os.remove('file.txt')

# 创建目录
os.makedirs('path/to/dir', exist_ok=True)

八、文件模式总结 #

模式 说明
'r' 只读(默认)
'w' 只写(覆盖)
'a' 追加
'x' 创建(存在则报错)
'b' 二进制
'+' 读写
最后更新:2026-03-16