当前位置: 首页 > news >正文

Python入门第八课:学会文件操作,让数据持久化存储

课程目标

  • 掌握文件的打开和关闭

  • 学会文件的读写操作

  • 理解异常处理机制

  • 掌握with语句的使用

一、文件基础操作

1.1 文件的打开和关闭

文件操作是程序与外部世界交流的重要方式。Python使用open()函数来打开文件,操作完成后需要关闭文件。

# 打开文件的基本方法
file = open("example.txt", "r")  # 以只读模式打开
content = file.read()           # 读取文件内容
file.close()                    # 关闭文件print(content)

1.2 文件打开模式

不同的打开模式决定了文件的操作权限,选择正确的模式很重要。

# 各种打开模式示例
"""
r: 只读模式(默认)
w: 写入模式,会覆盖原有内容
a: 追加模式,在文件末尾添加
x: 创建模式,文件存在则报错
b: 二进制模式
t: 文本模式(默认)
+: 读写模式
"""# 实际使用
file1 = open("data.txt", "w")  # 写入模式
file2 = open("data.txt", "a")  # 追加模式  
file3 = open("data.txt", "r+") # 读写模式

二、文件读写操作

2.1 读取文件内容

Python提供了多种读取文件的方法,适用于不同场景。

# 读取整个文件
with open("example.txt", "r", encoding="utf-8") as file:content = file.read()print("整个文件内容:")print(content)# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:print("\n逐行读取:")line = file.readline()while line:print(line.strip())  # strip()去除换行符line = file.readline()# 读取所有行到列表
with open("example.txt", "r", encoding="utf-8") as file:lines = file.readlines()print("\n所有行:")for i, line in enumerate(lines, 1):print(f"{i}: {line.strip()}")

2.2 写入文件内容

写入文件时要注意打开模式,'w'模式会覆盖,'a'模式会追加。

# 写入文件
with open("output.txt", "w", encoding="utf-8") as file:file.write("这是第一行\n")file.write("这是第二行\n")file.write("这是第三行\n")print("文件写入完成")# 追加内容
with open("output.txt", "a", encoding="utf-8") as file:file.write("这是追加的内容\n")file.write("这也是追加的内容\n")print("内容追加完成")# 写入多行
lines = ["第一行", "第二行", "第三行"]
with open("multi_line.txt", "w", encoding="utf-8") as file:file.writelines(line + "\n" for line in lines)print("多行写入完成")

三、异常处理

3.1 基本异常处理

文件操作可能遇到各种错误,使用try-except可以优雅地处理这些异常。

# 基本的异常处理
try:file = open("nonexistent.txt", "r")content = file.read()file.close()
except FileNotFoundError:print("文件不存在!")
except PermissionError:print("没有文件访问权限!")
except Exception as e:print(f"发生错误: {e}")# 更完整的异常处理
try:with open("data.txt", "r") as file:content = file.read()number = int(content)  # 可能引发ValueError
except FileNotFoundError:print("文件不存在,创建新文件")with open("data.txt", "w") as file:file.write("0")
except ValueError:print("文件内容不是有效数字")
except Exception as e:print(f"未知错误: {e}")
else:print("文件读取成功")
finally:print("文件操作结束")

3.2 自定义异常处理

可以创建更具体的异常处理逻辑来应对不同的错误情况。

def read_file_safely(filename):"""安全读取文件函数"""try:with open(filename, "r", encoding="utf-8") as file:return file.read()except FileNotFoundError:return f"错误:文件 {filename} 不存在"except PermissionError:return "错误:没有文件访问权限"except UnicodeDecodeError:return "错误:文件编码问题"except Exception as e:return f"未知错误:{e}"# 测试异常处理
result1 = read_file_safely("example.txt")
result2 = read_file_safely("nonexistent.txt")
print(result1)
print(result2)

四、with语句和实战应用

4.1 with语句的优势

with语句会自动管理文件的打开和关闭,即使发生异常也能正确关闭文件。

# 传统方式 vs with语句
# 传统方式需要手动关闭
file = open("test.txt", "w")
file.write("Hello")
file.close()  # 容易忘记关闭# with语句自动管理
with open("test.txt", "w") as file:file.write("Hello")
# 文件会自动关闭# 同时操作多个文件
with open("source.txt", "r") as source, open("backup.txt", "w") as backup:content = source.read()backup.write(content)print("文件备份完成")

4.2 实战应用:日记本程序

结合文件操作和之前学过的知识,创建一个实用的日记本程序。

def diary_program():"""简单的日记本程序"""def write_diary():"""写日记"""date = input("请输入日期(YYYY-MM-DD): ")content = input("请输入日记内容: ")with open("diary.txt", "a", encoding="utf-8") as file:file.write(f"{date}\n")file.write(f"{content}\n")file.write("-" * 40 + "\n")print("日记保存成功!")def read_diary():"""读日记"""try:with open("diary.txt", "r", encoding="utf-8") as file:content = file.read()if content:print("\n=== 我的日记 ===")print(content)else:print("还没有日记内容")except FileNotFoundError:print("还没有日记文件")def show_statistics():"""显示统计信息"""try:with open("diary.txt", "r", encoding="utf-8") as file:lines = file.readlines()diary_count = lines.count("-" * 40 + "\n")word_count = sum(len(line.split()) for line in lines)print(f"日记篇数: {diary_count}")print(f"总字数: {word_count}")except FileNotFoundError:print("还没有日记文件")# 主程序循环while True:print("\n=== 日记本程序 ===")print("1. 写日记")print("2. 读日记")print("3. 统计信息")print("4. 退出")choice = input("请选择操作: ")if choice == "1":write_diary()elif choice == "2":read_diary()elif choice == "3":show_statistics()elif choice == "4":print("再见!")breakelse:print("无效选择")# 运行日记本程序
diary_program()

五、综合练习

练习:学生成绩文件管理

创建一个能够将学生成绩保存到文件并从中读取的系统。

def student_grade_manager():"""学生成绩文件管理系统"""def save_students(students):"""保存学生数据到文件"""with open("students.txt", "w", encoding="utf-8") as file:for student in students:line = f"{student['name']},{student['score']}\n"file.write(line)print("学生数据保存成功")def load_students():"""从文件加载学生数据"""students = []try:with open("students.txt", "r", encoding="utf-8") as file:for line in file:if line.strip():  # 跳过空行name, score = line.strip().split(",")students.append({"name": name,"score": int(score)})except FileNotFoundError:print("还没有学生数据文件")return studentsdef add_student(students):"""添加学生"""name = input("请输入学生姓名: ")score = int(input("请输入学生成绩: "))students.append({"name": name, "score": score})save_students(students)def show_students(students):"""显示所有学生"""if not students:print("没有学生数据")returnprint("\n=== 学生列表 ===")for student in students:print(f"{student['name']}: {student['score']}分")# 主程序students = load_students()while True:print("\n=== 学生成绩管理系统 ===")print("1. 添加学生")print("2. 显示学生")print("3. 退出")choice = input("请选择操作: ")if choice == "1":add_student(students)elif choice == "2":show_students(students)elif choice == "3":print("再见!")breakelse:print("无效选择")# 运行系统
student_grade_manager()

六、重点总结

文件打开模式:

"r" - 只读
"w" - 写入(覆盖)
"a" - 追加
"r+" - 读写

文件操作方法:

file.read()      # 读取全部内容
file.readline()  # 读取一行
file.readlines() # 读取所有行
file.write()     # 写入内容
file.writelines() # 写入多行

异常处理语法:

try:# 可能出错的代码
except ExceptionType:# 处理异常
finally:# 无论是否异常都会执行

with语句优势:

  • 自动管理文件关闭

  • 代码更简洁

  • 异常安全

课后练习

  1. 创建一个通讯录程序,将联系人保存到文件

  2. 编写一个文件备份程序,能够备份指定文件

  3. 制作一个简单的日志记录系统


下节预告:面向对象编程入门 - 学习类和对象的概念

http://www.dtcms.com/a/487667.html

相关文章:

  • 四川建设数字证书网站付费查看下载wordpress虚拟资源
  • 溧水做网站汕头建站方案
  • 网站制作学什么软件东城企业网站开发
  • 【机器视觉-基础知识】三角测量(Triangulation)
  • 三轴云台之构图优化技术篇
  • 酒店官方网站的功能建设温州外贸网站建设公司
  • [记录]whisper-diarization自动语音识别与说话人分离
  • 正规网站优化推广如何提升网站搜索排名
  • day11_web应用构建
  • 网站开发项目流程图基于推荐算法的网站开发
  • LeetCode 3350. 检测相邻递增子数组 II
  • 【底层机制】【Android】深入理解UI体系与绘制机制
  • 注册一个软件需要多少钱牡丹江网站seo
  • 高校英文网站建设贵阳网站推广有几家
  • 建设一个网络交友的网站的论文网站系统有哪些
  • Echarts【图表生成】
  • #深入解析Golang命令行框架Cobra:构建强大的CLI应用
  • 智能体开发基础
  • 亚当学院网站视频建设教程wordpress flash插件下载
  • 矩阵奇异值分解算法(SVD)的导数 / 灵敏度分析
  • 如何查看一个网站是不是用h5做的怎样做企业营销网站
  • Valentina Studio:一款跨平台的数据库管理工具
  • Jmeter接口测试与压力测试
  • 网站建设公司营业执照经营范围网推是干嘛的
  • 合规化短剧分销系统开发:用户数据保护、佣金税务合规与内容版权风险规避
  • 手机网站封装用户体验做问卷网站好
  • 算法性能的核心度量:时间复杂度与空间复杂度深度解析
  • 【shell】每日shell练习(系统用户安全审计/系统日志错误分析)
  • 【Kylin V10】SSLERRORSYSCALL 的修复方法
  • 注册一个网站域名一年需要多少钱夏县网站建设