网站首页 > 技术文章 正文
文件操作 的内容,包括读写文本文件、使用 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 是智能助手,让你不用操心关门。练习让我学会把内存里的数据存到硬盘,再拿回来用,感觉很实用!
如果有疑问,或者想加点功能(比如追加成绩、处理多个文件),随时告诉我哦!
猜你喜欢
- 2025-03-28 Python os模块完全指南:轻松玩转文件管理与系统操作
- 2025-03-28 和尧名大叔一起从0开始学Python编程-简单读写文件
- 2025-03-28 【高效办公系列】一步一步教你使用Python下载文件
- 2025-03-28 如何用python打开文件(python怎样打开文件夹)
- 2025-03-28 Python内容写入excel文件(Excel写入)
- 2025-03-28 自动化文件管理的6个Python脚本模板
- 2025-03-28 Python读取配置文件(config.ini),写入配置文件
- 2025-03-28 第41讲 基本文件操作(和猫妹学Python)
- 2025-03-28 一日一技:python中的文件处理(01)
- 2025-03-28 [oeasy]python0010_怎么用命令行保存文件
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)