文件操作与异常处理
对应教学日历:讲次 8-9
一、文件打开与关闭
打开文件
handle = open("D:\\exam\\test.txt", 'r') # 指定路径
handle = open("test.txt", 'r') # 当前目录关闭文件
handle.close()with 语句(推荐)
with open("test.txt", "r", encoding="utf-8") as fobj:
content = fobj.read()
# 自动关闭文件打开模式
| 模式 | 说明 |
|---|---|
"r" | 只读(默认) |
"w" | 写入(覆盖原文件) |
"a" | 追加写入 |
"r+" | 读写 |
"w+" | 写读(覆盖) |
"a+" | 追加读写 |
二、文件读操作
read() — 读取整个文件
with open("english.txt", "r", encoding="utf-8") as fobj:
paper = fobj.read()readline() — 读取一行
with open("data.txt", "r") as fobj:
line = fobj.readline()readlines() — 读取所有行到列表
with open("data.csv", "r") as fobj:
lines = fobj.readlines()直接遍历文件(推荐)
with open("data.csv", "r") as fobj:
for line in fobj:
line = line.strip()
print(line)三、文件写操作
write() — 写入字符串
with open("new.txt", 'w') as handle:
handle.write("Hello World\n")writelines() — 写入字符串列表
string = ["hello\n", "world\n"]
with open("new.txt", 'w') as handle:
handle.writelines(string)四、CSV文件处理
读取CSV数据
lab = []
with open("data.csv", "r") as fobj:
for i in fobj:
i = i.strip()
i = float(i)
lab.append(i)
print("最高值为:{:.2f}".format(max(lab)))按列读取CSV
with open("student.csv", "r") as fobj:
for i in fobj:
if i[:2] == "学号": # 跳过表头
continue
info = i.strip().split(",")
print(info[1]) # 第2列(姓名)统计CSV数据
count = 0
total = 0
name = input("请输入大类名称:")
with open("competition.csv", "r") as fobj:
for eachLine in fobj:
if eachLine[:4] == "作品编号":
continue
total = total + 1
line = eachLine.split(",")
if line[1] == name:
count = count + 1
if count != 0:
print("该大类参赛作品总共为:{}".format(count))
print("占比为:{:.1f}".format(count / total))五、异常处理
try:
<语句块1>
except <异常类型>:
<语句块2>
else:
<语句块3> # 无异常时执行
finally:
<语句块4> # 总是执行除数为零错误
try:
num1 = int(input("The first number:"))
num2 = int(input("The second number:"))
num3 = num1 / num2
print(num3)
except ZeroDivisionError:
print("除数为零错误")文件不存在错误
try:
with open("二十大报告.txt", "r", encoding='utf-8') as fobj:
paper = fobj.read()
print(paper)
except FileNotFoundError:
print("文件不存在")作业示例
文章单词替换并保存
with open("english.txt", 'r') as fobj:
paper = fobj.read()
content = paper.replace("mouse", "bird")
with open("new.txt", 'w') as handle:
handle.write(content + '\n')批量手机号码加密
aList = []
with open('ph.txt', 'r') as fobj:
for number in fobj:
new = number[:3] + "****" + number[7:]
aList.append(new)
with open('result.txt', 'w') as fobj:
fobj.writelines(aList)学生成绩处理
scores = []
with open("myscore.txt", "r", encoding="utf-8") as fobj:
for eachLine in fobj:
if eachLine[:2] == "姓名":
continue
line = eachLine.split()
scores.append(int(line[1]))
ave = sum(scores) / len(scores)
print(f"The average score of English is {ave:.1f}")随机点名程序
import time
import random
count = int(input("请输入随机点名人数:"))
namelist = []
with open("student.csv", "r") as fobj:
for i in fobj:
if i[:2] == "学号":
continue
info = i.strip().split(",")
namelist.append(info[1])
result = random.sample(namelist, count)
time.sleep(1)
for i in result:
print("{}请回答问题".format(i))作业重点
with open()自动关闭文件,推荐使用read()读全部,readline()读一行,readlines()读所有行到列表write()不自动换行,需要手动加\nwritelines()写入字符串列表,不自动加换行符- CSV处理:
strip()去换行符,split(",")按逗号分割 - 跳过表头:
if line[:2] == "姓名": continue try-except捕获异常,finally总是执行FileNotFoundError文件不存在,ZeroDivisionError除零