文件操作基础
读写、路径、JSON、异常
读取整个文件
with open("访客列表.txt", encoding="utf8") as fin:
content = fin.read()
print(content)
按行读取
with open("访客列表.txt", encoding="utf8") as fin:
for line in fin:
line = line[:-1]去掉每一行的最后一个元素
line = line.rstrip()
print(line)
写出文件
with open("数字列表.txt", "w", encoding="utf8") as fout:
for i in range(100):
fout.write(str(i) + "\n")
练习题 .py
英汉词典 英汉词典.py
- 读取 英汉词典.txt
- 构建 dict,查询
- 循环至 quit
婚礼礼金 婚礼礼金程序.py
- 写入 婚礼礼金.txt
- 统计加和/最高/最低/平均
成绩录入json 成绩录入json.py
- 加载 成绩录入json.txt
- 录入姓名 成绩,存 dict
- json.dumps 保存
异常处理成绩 异常处理学生成绩.py
- 录入姓名 成绩
- try/except 捕获非数字
- 提示异常,继续录入
路径 & JSON
路径处理: 绝对/相对,os.path.exists,r"raw\string"
import os, json
file_path = r"D:\data\file.txt"
if os.path.exists(file_path):
with open(file_path, encoding="utf8") as f:
data = json.loads(f.read())
异常处理
try:
grade = int(input("请输入成绩:"))
except ValueError as e:
print("无效输入:", e)
所有 .py 附课件
输出 .txt / .json
with 管理资源