在 Python 中,文件操作是常见的基础功能,主要通过内置的 open() 函数以及文件对象的方法来实现。以下是常用的文件操作方法分类说明:

一、打开文件:open() 函数

用于创建文件对象,语法:

file = open(file_path, mode, encoding)
  • 1.
  • file_path:文件路径(相对或绝对路径)
  • mode:打开模式(常用模式如下)
  • 'r':只读(默认),文件不存在则报错
  • 'w':写入(覆盖原有内容),文件不存在则创建
  • 'a':追加写入(在文件末尾添加),文件不存在则创建
  • 'r+':读写模式
  • 'b':二进制模式(如 'rb' 读二进制文件,'wb' 写二进制文件)
  • encoding:编码格式(如 encoding='utf-8',文本模式下使用)
二、文件对象的常用方法
1. 读取方法
  • read(size):读取指定字节数(size 省略则读取全部内容)
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read(100)  # 读取前100字节
    print(content)
  • 1.
  • 2.
  • 3.
  • readline():读取一行内容(包括换行符 \n)
with open("test.txt", "r") as f:
    line1 = f.readline()  # 读第一行
    line2 = f.readline()  # 读第二行
  • 1.
  • 2.
  • 3.
  • readlines():读取所有行,返回列表(每行作为列表元素)
with open("test.txt", "r") as f:
    lines = f.readlines()  # 列表形式存储所有行
    for line in lines:
        print(line.strip())  # 去除换行符
  • 1.
  • 2.
  • 3.
  • 4.
  • 迭代文件对象(高效读取大文件)
with open("large_file.txt", "r") as f:
    for line in f:  # 逐行迭代,内存友好
        print(line)
  • 1.
  • 2.
  • 3.
2. 写入方法
  • write(string):写入字符串(返回写入的字符数)
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, Python!\n")  # 写入内容并换行
    f.write("文件操作示例")
  • 1.
  • 2.
  • 3.
  • writelines(iterable):写入可迭代对象(如列表、元组)
lines = ["第一行\n", "第二行\n", "第三行"]
with open("output.txt", "a") as f:
    f.writelines(lines)  # 追加写入多行
  • 1.
  • 2.
  • 3.
3. 其他常用方法
  • close():关闭文件(释放资源,推荐用 with 语句自动关闭)
f = open("test.txt", "r")
content = f.read()
f.close()  # 手动关闭
  • 1.
  • 2.
  • 3.
  • flush():强制刷新缓冲区(立即将数据写入文件,不等待缓冲区满)
with open("log.txt", "a") as f:
    f.write("实时日志...")
    f.flush()  # 立即写入磁盘
  • 1.
  • 2.
  • 3.
  • seek(offset, whence):移动文件指针(用于随机访问)
  • offset:偏移量(字节数)
  • whence:起始位置(0:文件开头,1:当前位置,2:文件末尾)
with open("test.txt", "r+") as f:
    f.seek(5)  # 从开头移动5字节
    content = f.read(3)  # 读取从第5字节开始的3个字符
  • 1.
  • 2.
  • 3.
  • tell():返回当前文件指针位置(字节数)
with open("test.txt", "r") as f:
    f.read(10)
    print(f.tell())  # 输出:10(当前指针在第10字节处)
  • 1.
  • 2.
  • 3.
  • truncate(size):截断文件到指定字节数(默认截断到当前指针位置)
with open("test.txt", "r+") as f:
    f.truncate(50)  # 保留前50字节,其余删除
  • 1.
  • 2.
三、上下文管理器(推荐用法)

使用 with 语句操作文件,会自动关闭文件,避免资源泄露:

with open("file.txt", "r") as f:
    # 操作文件
    content = f.read()
# 离开with块后,文件自动关闭
  • 1.
  • 2.
  • 3.
  • 4.
四、常见文件操作场景
  1. 读取文本文件
with open("data.txt", "r", encoding="utf-8") as f:
    print(f.read())
  • 1.
  • 2.
  1. 写入文本文件
with open("result.txt", "w", encoding="utf-8") as f:
    f.write("写入内容")
  • 1.
  • 2.
  1. 复制文件(二进制模式)
with open("source.jpg", "rb") as src, open("copy.jpg", "wb") as dst:
    dst.write(src.read())  # 二进制读写
  • 1.
  • 2.

以上是 Python 文件操作的核心方法,掌握这些可以满足大部分日常文件处理需求。