# 第7课:文件读写 —— 让数据"活"起来
# 1.写入文件(w模式:覆盖写入)
file = open("test.txt", "w", encoding="utf-8")
file.write("第一行:Hello Python!\n")
file.write("第二行:文件读写真有趣\n")
file.close() # 写完必须关闭,否则内容可能丢失
print("写入完成!")
print()
# 2.读取文件(r模式:只读)
file = open("test.txt", "r", encoding="utf-8")
content = file.read() # 一次性读取全部内容
print(content)
file.close()
print()
# 3.逐行读取
file = open("test.txt", "r", encoding="utf-8")
line1 = file.readline() # 读一行
line2 = file.readline() # 再读一行
print(f"第一行:{line1}", end="") # end=""因为原文本已有换行
print(f"第二行:{line2}", end="")
file.close()
print()
print()
# 4.读取所有行成列表
file = open("test.txt", "r", encoding="utf-8")
lines = file.readlines() # 返回列表,每行一个元素
print(lines) # ['第一行:Hello Python!\n', '第二行:文件读写真有趣\n']
for line in lines:
print(f"→ {line}", end="")
file.close()
print()
print()
# 5.追加写入(a模式:在末尾追加,不覆盖)
file = open("test.txt", "a", encoding="utf-8")
file.write("第三行:追加的新内容\n")
file.close()
# 验证追加结果
file = open("test.txt", "r", encoding="utf-8")
print(file.read())
file.close()
# 6.用with自动关闭文件(推荐写法!)
print("=== 用with写入 ===")
with open("diary.txt", "w", encoding="utf-8") as f:
f.write("2026年5月29日 晴\n")
f.write("今天学了文件读写!\n")
# 离开with代码块,文件自动关闭,不需要手动close
print("=== 用with读取 ===")
with open("diary.txt", "r", encoding="utf-8") as f:
print(f.read())
# 7.实战:通讯录数据保存到文件
import os
contacts = []
def load_contacts():
"""从文件加载通讯录"""
global contacts
if os.path.exists("contacts.txt"):
with open("contacts.txt", "r", encoding="utf-8") as f:
for line in f:
# 每行格式:姓名,电话
parts = line.strip().split(",")
if len(parts) == 2:
contacts.append({"name": parts[0], "phone": parts[1]})
print(f"已加载 {len(contacts)} 条联系人")
else:
print("通讯录为空,从零开始")
def save_contacts():
"""保存通讯录到文件"""
with open("contacts.txt", "w", encoding="utf-8") as f:
for c in contacts:
f.write(f"{c['name']},{c['phone']}\n")
print("通讯录已保存!")
def add_contact(name, phone):
"""添加联系人"""
contacts.append({"name": name, "phone": phone})
save_contacts()
print(f"已添加:{name} - {phone}")
def show_contacts():
"""显示所有联系人"""
if not contacts:
print("通讯录为空")
return
print("--- 通讯录 ---")
for i, c in enumerate(contacts, 1):
print(f"{i}. {c['name']} - {c['phone']}")
# 测试运行
load_contacts()
add_contact("火鸟", "1351866756")
add_contact("小明", "13900139000")
show_contacts()
知识点速查
| 知识点 | 关键代码 | 作用 |
|---|---|---|
| 捕获异常 | try...except |
出错不崩溃 |
| 获取错误信息 | except ValueError as e |
知道具体哪里错了 |
| 完整结构 | try-except-else-finally |
分情况处理 |
| 主动抛异常 | raise ValueError("原因") |
自己定义错误 |
| 内置模块 | import random/time |
直接用 |
| 从模块导入 | from datetime import datetime |
只导入需要的 |
| 第三方模块 | pip install 模块名 |
需要先安装 |
未经允许不得转载:百花谷博客 » 跟着AI学Python 第7课:文件读写

百花谷博客
微信关注,获取更多