之前学的知识,程序一关闭就全没了。今天,我们来学 —— 文件读写,让程序能把数据存到文件里,下次打开还能「记得」!
一、为什么要学文件读写?
想象一下:
-
- 你做了一个「学生成绩管理系统」,每次都要重新输入成绩,太累了!
-
- 如果能存到文件里,下次打开直接读取,多方便!
-
二、写文件 —— open() 和 write()
# 打开文件,写入内容
file = open("hello.txt", "w") # "w" = write(写入模式)
file.write("你好,世界!")
file.close() # 记得关闭文件# 运行后,会创建一个 hello.txt 文件,内容是:你好,世界!
⚠️ 注意:"w" 模式会覆盖原有内容!
三、读文件 —— read()
file = open("hello.txt", "r") # "r" = read(读取模式)
content = file.read()
print(content)
file.close()你好,世界!
四、追加内容 —— "a" 模式
不想覆盖,只想在末尾添加?用 "a"(append)模式:
file = open("hello.txt", "a")
file.write("\n这是新添加的内容!") # \n 是换行符
file.close()你好,世界!
这是新添加的内容!
五、with 语句 —— 自动关闭文件
经常忘记 close()?用 with 语句,文件会自动关闭:
# 写入
with open("scores.txt", "w") as file:
file.write("小明:95\n")
file.write("小红:88\n")
file.write("小刚:92\n")
# 读取
with open("scores.txt", "r") as file:
content = file.read()
print(content)小明:95
小红:88
小刚:92
六、逐行读取 —— readlines()
with open("scores.txt", "r") as file:
lines = file.readlines() # 返回一个列表
for line in lines:
print(line.strip()) # strip() 去掉换行符小明:95
小红:88
小刚:92
七、实战:学生成绩管理系统
# 添加成绩
def add_score(name, score):
with open("scores.txt", "a") as file:
file.write(f"{name}:{score}\n")
print(f"已添加 {name} 的成绩:{score}分")
# 查看所有成绩
def show_scores():
try:
with open("scores.txt", "r") as file:
print("===== 成绩表 =====")
for line in file:
print(line.strip())
except FileNotFoundError:
print("还没有成绩记录!")
# 计算平均分
def get_average():
try:
with open("scores.txt", "r") as file:
total = 0
count = 0
for line in file:
parts = line.strip().split(":")
total += int(parts[1])
count += 1
print(f"平均分:{total/count:.1f}分")
except FileNotFoundError:
print("还没有成绩记录!")
# 使用
add_score("小明", 95)
add_score("小红", 88)
add_score("小刚", 92)
show_scores()
get_average()已添加 小明 的成绩:95分
已添加 小红 的成绩:88分
已添加 小刚 的成绩:92分
===== 成绩表 =====
小明:95
小红:88
小刚:92
平均分:91.7分
八、文件模式总结
| 模式 | 含义 | 特点 |
| "r" | 读取 | 文件必须存在 |
| "w" | 写入 | 覆盖原有内容 |
| "a" | 追加 | 在末尾添加 |
九、练习题
练习1:创建一个日记本程序
with open("diary.txt", "a") as file:
diary = input("今天发生了什么?")
file.write(diary + "\n")
print("日记已保存!")练习2:统计文件有多少行
with open("scores.txt", "r") as file:
lines = file.readlines()
print(f"共有 {len(lines)} 条记录")十、今天学到了什么?
-
- 打开文件:open("文件名", "模式")
-
- 写入:write(),读取:read()
-
- 三种模式:r(读)、w(写)、a(追加)
-
- with 语句:自动关闭文件
-
- readlines():逐行读取
-
十一、下期预告
学会了文件读写,下节课我们来学 —— 异常处理,让程序遇到错误时不崩溃,优雅地处理!
敬请期待:《小学生Python:异常处理 —— 让程序更健壮》
喜欢这篇文章吗?点个「在看」,让更多小朋友学会用 Python 保存数据!