Skip to content

第13章:文件操作

13.1 文件操作的意义

文件操作是Python编程中的重要内容,它允许程序与外部文件进行交互,实现数据的持久化存储和读取。文件操作的主要意义包括:

  • 数据持久化:将程序运行过程中的数据保存到文件中,程序结束后数据不会丢失
  • 数据交换:与其他程序或系统交换数据
  • 配置管理:存储程序的配置信息
  • 日志记录:记录程序运行过程中的信息和错误
  • 批量处理:处理大量文本或数据文件

13.2 文件操作的基本流程

文件操作的基本流程包括三个步骤:打开文件 → 操作文件 → 关闭文件。

  1. 打开文件:使用open()函数打开文件,获取文件对象
  2. 操作文件:对文件进行读取或写入操作
  3. 关闭文件:使用close()方法关闭文件,释放资源

13.3 文件打开与关闭

打开文件

使用open()函数打开文件,语法如下:

python
open(文件名, 打开模式, 编码)
  • 文件名:文件的路径(相对路径或绝对路径)
  • 打开模式:文件的打开方式,如读取、写入等
  • 编码:文件的编码方式,如utf-8

打开模式

模式描述
r只读模式(默认),文件必须存在
w写入模式,会覆盖原有内容,文件不存在则创建
a追加模式,在文件末尾添加内容,文件不存在则创建
r+读写模式,文件必须存在
w+读写模式,会覆盖原有内容,文件不存在则创建
a+读写模式,在文件末尾添加内容,文件不存在则创建
b二进制模式,与其他模式组合使用,如rbwb

关闭文件

使用close()方法关闭文件,释放资源:

python
file = open("test.txt", "r")
# 操作文件
file.close()  # 关闭文件

推荐方式:with语句

使用with语句可以自动关闭文件,避免遗漏:

python
with open("test.txt", "r", encoding="utf-8") as f:
    # 操作文件
    content = f.read()
# 文件自动关闭

13.4 文件读写操作

读取文件

  • read():读取文件的全部内容
  • readline():读取文件的一行内容
  • readlines():读取文件的所有行,返回一个列表

示例:

python
# 读取全部内容
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

# 读取一行内容
with open("test.txt", "r", encoding="utf-8") as f:
    line = f.readline()
    print(line)

# 读取所有行
with open("test.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())

# 逐行读取(推荐,内存友好)
with open("test.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

写入文件

  • write():写入字符串
  • writelines():写入字符串列表

示例:

python
# 写入字符串
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("Hello, Python!\n")
    f.write("Welcome to file operations.\n")

# 写入字符串列表
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("test.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)

# 追加内容
with open("test.txt", "a", encoding="utf-8") as f:
    f.write("追加的内容\n")

13.5 常见文件类型操作

文本文件(.txt)

文本文件是最常见的文件类型,用于存储文本数据。

示例:读取文本文件内容

python
def read_text_file(filename):
    """读取文本文件内容"""
    try:
        with open(filename, "r", encoding="utf-8") as f:
            content = f.read()
            print(f"文件内容:\n{content}")
    except FileNotFoundError:
        print(f"文件{filename}不存在!")
    except Exception as e:
        print(f"读取文件时出错:{e}")

read_text_file("test.txt")

示例:写入用户信息到文件

python
def write_user_info(filename, users):
    """写入用户信息到文件"""
    with open(filename, "w", encoding="utf-8") as f:
        for user in users:
            f.write(f"姓名:{user['name']}, 年龄:{user['age']}, 邮箱:{user['email']}\n")

# 测试
users = [
    {"name": "张三", "age": 18, "email": "zhangsan@example.com"},
    {"name": "李四", "age": 20, "email": "lisi@example.com"},
    {"name": "王五", "age": 22, "email": "wangwu@example.com"}
]

write_user_info("user_info.txt", users)
print("用户信息已写入文件")

CSV文件(.csv)

CSV(Comma-Separated Values)文件是一种常见的表格数据存储格式,使用逗号分隔值。

示例:读取CSV文件数据

python
def read_csv_file(filename):
    """读取CSV文件数据"""
    try:
        with open(filename, "r", encoding="utf-8") as f:
            # 读取表头
            header = f.readline().strip().split(",")
            print(f"表头:{header}")
            
            # 读取数据行
            print("数据:")
            for line in f:
                data = line.strip().split(",")
                print(data)
    except FileNotFoundError:
        print(f"文件{filename}不存在!")

# 测试
read_csv_file("data.csv")

示例:写入CSV文件数据

python
def write_csv_file(filename, header, data):
    """写入CSV文件数据"""
    with open(filename, "w", encoding="utf-8") as f:
        # 写入表头
        f.write(",".join(header) + "\n")
        
        # 写入数据行
        for row in data:
            f.write(",".join(map(str, row)) + "\n")

# 测试
header = ["姓名", "年龄", "邮箱"]
data = [
    ["张三", 18, "zhangsan@example.com"],
    ["李四", 20, "lisi@example.com"],
    ["王五", 22, "wangwu@example.com"]
]

write_csv_file("user_data.csv", header, data)
print("CSV文件已写入")

实操案例:批量处理文本文件

案例:批量处理文本文件

python
"""
批量处理文本文件
功能:读取多个文本文件,统计单词频率
"""

import os
import re

def count_words_in_file(filename):
    """统计文件中的单词频率"""
    word_count = {}
    try:
        with open(filename, "r", encoding="utf-8") as f:
            content = f.read()
            # 使用正则表达式提取单词
            words = re.findall(r'\b\w+\b', content.lower())
            for word in words:
                word_count[word] = word_count.get(word, 0) + 1
    except Exception as e:
        print(f"处理文件{filename}时出错:{e}")
    return word_count

def batch_process_files(directory):
    """批量处理目录中的文本文件"""
    if not os.path.exists(directory):
        print(f"目录{directory}不存在!")
        return
    
    all_word_count = {}
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            file_path = os.path.join(directory, filename)
            print(f"处理文件:{filename}")
            word_count = count_words_in_file(file_path)
            # 合并单词频率
            for word, count in word_count.items():
                all_word_count[word] = all_word_count.get(word, 0) + count
    
    # 按频率排序
    sorted_words = sorted(all_word_count.items(), key=lambda x: x[1], reverse=True)
    
    # 输出前10个高频单词
    print("\n高频单词:")
    for word, count in sorted_words[:10]:
        print(f"{word}: {count}")

# 测试
batch_process_files("text_files")

运行结果

处理文件:file1.txt
处理文件:file2.txt

高频单词:
the: 15
and: 10
to: 8
of: 7
in: 6
is: 5
it: 4
you: 4
that: 3
with: 3

新手易错点

  • 文件路径错误

    • 相对路径/绝对路径混淆
    • 路径分隔符使用错误(Windows使用\,Linux使用/
    • 建议使用os.path模块处理路径
  • 编码错误

    • 未指定encoding="utf-8",导致读取中文文件时出现乱码
    • 不同文件的编码不一致
  • 忘记关闭文件

    • 未使用close()方法关闭文件,导致资源泄漏
    • 推荐使用with语句自动关闭文件
  • 写入模式使用错误

    • 误用w模式覆盖文件内容
    • 应该使用a模式追加内容
  • 文件操作异常

    • 未处理文件不存在、权限不足等异常
    • 建议使用try-except语句捕获异常

通过本章的学习,你已经掌握了Python中文件操作的基本方法。文件操作是Python编程中的重要内容,它允许程序与外部文件进行交互,实现数据的持久化存储和读取。在实际编程中,你会经常用到文件操作来处理各种数据文件。

© 2026 编程马·菜鸟教程 版权所有