第11讲 · 读取与写入文本文件
读取与写入文本文件
读取已有内容,覆盖或追加写入,并打开文件检查最终结果。
1读取文件中的已有内容
2覆盖或追加写入新内容
3打开文件检查最终结果
用 open() 选择读写模式
1r:读取已有文件
2w:覆盖写入文件
3a:在文件末尾追加内容
语法拆解
- open(path, "r", encoding="utf-8")
- 读取文本
- open(path, "w", encoding="utf-8")
- 覆盖写入
- open(path, "a", encoding="utf-8")
- 追加写入
用 read() 读取完整内容
l11_read_all.py
with open(path, "r", encoding="utf-8") as file:
content = file.read()
print(content)- open(path, "r", encoding="utf-8")
- 以只读方式打开
- content = file.read()
- 读取全部剩余内容
1r模式不会修改文件
2read返回一个完整字符串
3短文本可以一次读取
用 readline() 读取一行
l11_readline.py
import os
WORKSPACE = "/tmp/lesson11_workspace"
os.makedirs(WORKSPACE, exist_ok=True)
def prepare_text(filename, content):
path = os.path.join(WORKSPACE, filename)
with open(path, "w", encoding="utf-8") as fixture:
fixture.write(content)
return path
path = prepare_text("class_notes.txt", "第一行\n第二行\n第三行\n")
with open(path, "r", encoding="utf-8") as file:
first_line = file.readline()
second_line = file.readline()
print(repr(first_line))
print(repr(second_line))- line = file.readline()
- 读取当前位置的一行
- repr(line)
- 观察换行符
1每次只读取一行
2返回值通常带有换行符
3再次调用会继续读取下一行
用 for 逐行读取
l11_iterate_lines.py
import os
WORKSPACE = "/tmp/lesson11_workspace"
os.makedirs(WORKSPACE, exist_ok=True)
def prepare_text(filename, content):
path = os.path.join(WORKSPACE, filename)
with open(path, "w", encoding="utf-8") as fixture:
fixture.write(content)
return path
path = prepare_text("class_notes.txt", "读取文件\n写入文件\n检查结果\n")
with open(path, "r", encoding="utf-8") as file:
for number, line in enumerate(file, 1):
print(number, line.rstrip("\n"))- for line in file:
- 逐行读取文件
- line.rstrip('\n')
- 去掉行尾换行
1文件对象可以直接遍历
2每轮得到当前一行
3适合较长文本
用 w 模式覆盖写入
l11_write_new.py
with open(path, "w", encoding="utf-8") as file:
file.write("今天学习文件写入\n")
print("写入完成")- open(path, "w", encoding="utf-8")
- 覆盖方式打开
- file.write("今天学习文件写入\n")
- 写入新内容
1w会先清空旧内容
2write写入一个字符串
3写入内容需要自己添加换行符
打开文件检查写入结果
l11_check_write.py
import os
WORKSPACE = "/tmp/lesson11_workspace"
os.makedirs(WORKSPACE, exist_ok=True)
def prepare_text(filename, content):
path = os.path.join(WORKSPACE, filename)
with open(path, "w", encoding="utf-8") as fixture:
fixture.write(content)
return path
path = os.path.join(WORKSPACE, "class_notes.txt")
with open(path, "w", encoding="utf-8") as file:
file.write("Python可以修改文本文件\n")
with open(path, "r", encoding="utf-8") as file:
saved = file.read()
print("重新读取:", saved, end="")- file.write(content)
- 保存内容
- saved = file.read()
- 重新读取结果
1先完成写入
2再用r模式重新读取
3打开文件做可视化核对
用 a 模式追加内容
l11_append.py
import os
WORKSPACE = "/tmp/lesson11_workspace"
os.makedirs(WORKSPACE, exist_ok=True)
def prepare_text(filename, content):
path = os.path.join(WORKSPACE, filename)
with open(path, "w", encoding="utf-8") as fixture:
fixture.write(content)
return path
path = prepare_text("class_notes.txt", "原有笔记\n")
with open(path, "a", encoding="utf-8") as file:
file.write("追加笔记\n")
print("追加完成:", path)- open(path, "a", encoding="utf-8")
- 追加方式打开
- file.write("追加笔记\n")
- 写在末尾
1a保留原内容
2新文字写在文件末尾
3追加多行时显式写入换行符
比较 w 与 a 的文件变化
l11_compare_modes.py
import os
WORKSPACE = "/tmp/lesson11_workspace"
os.makedirs(WORKSPACE, exist_ok=True)
def prepare_text(filename, content):
path = os.path.join(WORKSPACE, filename)
with open(path, "w", encoding="utf-8") as fixture:
fixture.write(content)
return path
path = prepare_text("mode_demo.txt", "初始内容\n")
with open(path, "w", encoding="utf-8") as file:
file.write("覆盖后的内容\n")
with open(path, "a", encoding="utf-8") as file:
file.write("追加内容\n")
with open(path, "r", encoding="utf-8") as file:
print(file.read(), end="")- w → replace
- 覆盖原文件
- a → append
- 保留并追加
1w:替换整个文件内容
2a:在现有末尾继续写
3选择模式前先确认是否保留旧内容
用 with 自动关闭文件
l11_with_context.py
import os
WORKSPACE = "/tmp/lesson11_workspace"
os.makedirs(WORKSPACE, exist_ok=True)
def prepare_text(filename, content):
path = os.path.join(WORKSPACE, filename)
with open(path, "w", encoding="utf-8") as fixture:
fixture.write(content)
return path
path = os.path.join(WORKSPACE, "class_notes.txt")
with open(path, "w", encoding="utf-8") as file:
file.write("with会自动关闭文件\n")
print("代码块内已关闭:", file.closed)
print("代码块外已关闭:", file.closed)- with open(...) as file:
- 创建文件上下文
- file.closed
- 检查是否已经关闭
1进入with后文件处于打开状态
2离开缩进块后自动关闭
3读写代码更完整可靠
完成课堂笔记文件
先读取原始标题 · 用w写入整理后的内容 · 用a追加本节收获 · 打开文件完成验收
course_notes.py
with open(path, "w", encoding="utf-8") as file:
file.write(title + "\n- 文件读取\n")
with open(path, "a", encoding="utf-8") as file:
file.write("- 文件写入\n")verify_course_notes.py
import os
WORKSPACE = "/tmp/lesson11_workspace"
os.makedirs(WORKSPACE, exist_ok=True)
def prepare_text(filename, content):
path = os.path.join(WORKSPACE, filename)
with open(path, "w", encoding="utf-8") as fixture:
fixture.write(content)
return path
path = os.path.join(WORKSPACE, "course_notes.txt")
expected = "Python课堂笔记\n- 文件读取\n- 文件写入\n"
with open(path, "w", encoding="utf-8") as file:
file.write(expected)
with open(path, "r", encoding="utf-8") as file:
actual = file.read()
print("内容正确:", actual == expected)
print("文件已关闭:", file.closed)复盘文件读写流程
1定位文件:确认工作目录与目标路径
2读取文件:r配合read、readline或for
3写入文件:w覆盖,a追加
4关闭文件:统一使用with
5验收结果:重新读取并打开文件核对
语法拆解
- open → read
- 打开并读取
- open → write
- 覆盖或追加
- reopen → inspect
- 重新打开并验收
1 / 12