Skip to content

06 文件操作

📋 资料说明

  • 来源:课程 day06 前半
  • 笔记尚硅谷大模型技术之Python1.0.docx 第 7 章
  • 代码day06/代码/P01_File.pyP02_File_Copy.py
  • 视频:❌ 跳过(共 7 个视频:文件概念 → 打开/关闭 → 写入 → 读取 → os 模块 → 文件拷贝)

🟢 🤖 AI 替代率:98%

为什么是这个水平:

文件操作是纯 API 调用——open() 的 mode 参数、.read()/.write() 等方法的用法和参数都是确定性的。AI 可以精确给出任何文件操作场景的代码。

唯一需要人工判断的是:在不同编码环境下的乱码问题(特别是中文 Windows 下默认 GBK vs Python 默认 UTF-8)。这是系统环境导致的,不是 AI 知识盲区,但需要人在遇到时能识别。


👤 人工干预率:2%

几乎无需干预。建议记住一个原则:with 语句操作文件,它会自动关闭文件,避免资源泄漏。


1. 打开与关闭文件

python
# 打开文件
file = open("test.txt", "r", encoding="utf-8")
# ... 操作文件
file.close()  # 务必关闭,否则可能数据丢失或文件占用

# 推荐方式:with 语句(自动关闭)
with open("test.txt", "r", encoding="utf-8") as file:
    content = file.read()
# 离开 with 块自动关闭

文件打开模式

模式含义如果文件不存在写入位置
r只读(默认)报错
w只写创建覆盖
a追加创建末尾
x只写(排他)创建开头
r+读写报错开头
w+读写创建覆盖
a+读写追加创建末尾
python
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")

with open("test.txt", "a", encoding="utf-8") as f:
    f.write("World\n")

with open("test.txt", "r", encoding="utf-8") as f:
    print(f.read())  # Hello\nWorld\n

2. 读取文件

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:
    chunk = f.read(5)   # 读取前 5 个字符
    print(chunk)

# 读取一行
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()
    print(lines)

# 迭代器方式(推荐,适合大文件)
with open("test.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())  # strip() 去掉换行符

3. 写入文件

python
# 写入字符串
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("第一行\n")
    f.write("第二行\n")

# 写入多行
lines = ["line1\n", "line2\n", "line3\n"]
with open("output.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)

# 判断文件是否可写/可读
with open("output.txt", "r+", encoding="utf-8") as f:
    print(f.readable())   # True
    print(f.writable())   # True

4. 使用 os 模块(了解)

python
import os

# 当前工作目录
print(os.getcwd())

# 遍历目录树
for root, dirs, files in os.walk(os.getcwd()):
    print(f"当前路径: {root}")
    print(f"目录: {dirs}")
    print(f"文件: {files}")
    print()

# 常用方法
os.listdir(".")       # 列出当前目录所有文件
os.mkdir("newdir")    # 创建目录
os.remove("file.txt") # 删除文件
os.rename("old.txt", "new.txt")  # 重命名

5. 文件拷贝案例

python
def copy_file(src, dst):
    """拷贝文件"""
    with open(src, "rb") as f_src:    # 使用二进制模式
        with open(dst, "wb") as f_dst:
            # 分块拷贝,避免大文件内存溢出
            while True:
                chunk = f_src.read(4096)  # 每次读 4KB
                if not chunk:
                    break
                f_dst.write(chunk)

# 使用
copy_file("source.txt", "backup.txt")

练习题

练习 1:写入与读取

创建一个 notes.txt,写入 3 行文字,然后读取并打印全部内容。

练习 2:行号打印

读取一个文本文件,在每行前加上行号后输出。

练习 3:统计文件

读取任意文本文件,统计其中的字符数、行数和单词数。


参考答案

练习 1:

python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("第一行\n第二行\n第三行\n")

with open("notes.txt", "r", encoding="utf-8") as f:
    print(f.read())

练习 2:

python
with open("notes.txt", "r", encoding="utf-8") as f:
    for i, line in enumerate(f, 1):
        print(f"{i}: {line}", end="")

练习 3:

python
with open("notes.txt", "r", encoding="utf-8") as f:
    content = f.read()
    lines = content.splitlines()
    words = content.split()
    print(f"字符数: {len(content)}")
    print(f"行数: {len(lines)}")
    print(f"单词数: {len(words)}")

OPC 超级个体实战指南