python入门-day12: 文件操作
文件操作 的内容,包括读写文本文件、使用 with 语句,最后通过一个练习(将学生成绩保存到文件并读取)帮你把知识点串起来。我会用简单易懂的语言,确保新手也能轻松掌握。
Day 12: 文件操作
1. 读写文本文件(open、read、write)
- 什么是文件操作?
- 文件操作就是 Python 读写文件内容的技能,比如把数据保存到文件,或从文件读取数据。
- 就像在电脑上写日记(保存)或看日记(读取)。
- 打开文件:open()
- 用 open(文件名, 模式) 打开文件。
- 常用模式:
- 'r': 读取(默认模式),文件不存在会报错。
- 'w': 写入,会覆盖原内容,文件不存在会新建。
- 'a': 追加,写在文件末尾,不覆盖。
- 例子:
- python
- file = open("test.txt", "w") # 打开文件准备写入
- 读取文件:read()
- 用 read() 读取全部内容,或者用 readline() 读一行。
- 例子:
- python
- file = open("test.txt", "r") content = file.read() print(content) file.close() # 关闭文件
- 写入文件:write()
- 用 write() 把内容写入文件。
- 例子:
- python
- file = open("test.txt", "w") file.write("Hello, Python!") file.close() # 关闭文件
- 注意:
- 操作完文件要用 close() 关闭,否则可能数据没保存或占用资源。
2. with 语句
- 什么是 with 语句?
- with 是一种更安全的文件操作方式,自动关闭文件,不用手动写 close()。
- 就像借书时自动还书,不用担心忘记。
- 语法:
- python
- with open(文件名, 模式) as 文件对象: # 操作文件
- 例子:
- 写入:
- python
- with open("test.txt", "w") as file: file.write("Hello with Python!") # 文件自动关闭
- 读取:
- python
- with open("test.txt", "r") as file: content = file.read() print(content) # 输出: Hello with Python!
- 优点:
- 简洁、安全,即使代码出错,文件也会正确关闭。
3. 练习:将学生成绩保存到文件并读取
- 需求:
- 创建一个学生成绩字典。
- 把成绩保存到文件(比如 scores.txt)。
- 从文件读取成绩并显示。
- 代码实现:
python
# 学生成绩字典
scores = {
"小明": 95,
"小红": 88,
"小刚": 92
}
# 步骤 1:保存到文件
with open("scores.txt", "w") as file:
for name, score in scores.items():
file.write(f"{name}: {score}\n") # 每行写一个学生
print("成绩已保存到 scores.txt")
# 步骤 2:读取并显示
with open("scores.txt", "r") as file:
content = file.read()
print("读取的学生成绩:")
print(content)
- 代码说明:
- 保存: 用 with 打开文件写入模式,把字典里的键值对写成 "名字: 成绩" 的格式,每行一个。
- 读取: 用 with 打开文件读取模式,用 read() 读取全部内容并打印。
- 运行结果:
成绩已保存到 scores.txt
读取的学生成绩:
小明: 95
小红: 88
小刚: 92
- 生成的文件 scores.txt 内容:
小明: 95
小红: 88
小刚: 92
- 加点挑战:读取后还原成字典
python
# 保存成绩
scores = {"小明": 95, "小红": 88, "小刚": 92}
with open("scores.txt", "w") as file:
for name, score in scores.items():
file.write(f"{name}: {score}\n")
# 读取并还原成字典
new_scores = {}
with open("scores.txt", "r") as file:
for line in file: # 逐行读取
name, score = line.strip().split(": ") # 去掉换行符,按 ": " 分割
new_scores[name] = int(score) # 转成整数存入字典
print("还原后的字典:", new_scores)
- 运行结果:
还原后的字典: {'小明': 95, '小红': 88, '小刚': 92}
- 代码说明:
- 逐行读取: 用 for line in file 遍历每行。
- 处理行: 用 strip() 去掉换行符,split(": ") 分割成名字和成绩。
- 还原字典: 把成绩转成整数,存回字典。
完整练习代码
python
# 定义学生成绩
scores = {"小明": 95, "小红": 88, "小刚": 92}
# 保存到文件
with open("scores.txt", "w") as file:
for name, score in scores.items():
file.write(f"{name}: {score}\n")
print("成绩已保存到 scores.txt")
# 读取并显示
with open("scores.txt", "r") as file:
print("读取的学生成绩:")
print(file.read())
# 读取并还原成字典
new_scores = {}
with open("scores.txt", "r") as file:
for line in file:
name, score = line.strip().split(": ")
new_scores[name] = int(score)
print("还原后的字典:", new_scores)
总结
- 读写文件:
- open() 打开文件,read() 读取,write() 写入,close() 关闭。
- with 语句:
- 自动管理文件,省心又安全。
- 练习:
- 把字典保存到文件,像记账本一样;读取回来还原,像查账一样。
- 心得: 文件操作就像管理日记本,with 是智能助手,让你不用操心关门。练习让我学会把内存里的数据存到硬盘,再拿回来用,感觉很实用!
如果有疑问,或者想加点功能(比如追加成绩、处理多个文件),随时告诉我哦!