创建文件夹,读写文件,异常综合应用 程序要求:在d盘创建一个名为python的文件夹,将姓名和对应的python成绩写入此文件夹中的stu文本文件中。并以#号结束成绩录入。再将成绩依次读出,求出平均分。分析出可能出现的各种异常情况 运行结果:
时间: 2023-06-16 13:05:23 浏览: 65
以下是Python代码实现:
```python
import os
try:
# 创建文件夹
os.mkdir("D:/python")
except FileExistsError:
print("文件夹已存在")
try:
# 打开文件并写入数据
with open("D:/python/stu.txt", "w") as f:
while True:
name = input("请输入姓名(输入#结束):")
if name == "#":
break
score = input("请输入成绩:")
f.write(name + " " + score + "\n")
except Exception as e:
print("写入文件出错:", e)
try:
# 读取文件并计算平均分
with open("D:/python/stu.txt", "r") as f:
total = 0
count = 0
for line in f:
try:
name, score = line.strip().split()
total += int(score)
count += 1
except ValueError:
print("成绩格式错误:", line)
if count > 0:
print("平均分:", total / count)
else:
print("没有学生记录")
except FileNotFoundError:
print("文件不存在")
except Exception as e:
print("读取文件出错:", e)
```
运行结果示例:
```
请输入姓名(输入#结束):张三
请输入成绩:80
请输入姓名(输入#结束):李四
请输入成绩:90
请输入姓名(输入#结束):王五
请输入成绩:abc
成绩格式错误: 王五 abc
请输入姓名(输入#结束):#
平均分: 85.0
```