viewclass= input("choose a class number and either alphabetically, average or highest?")#type in what you want to select
if viewclass=='1 average':#variable inputted
with open("1.txt") as f:#open text file
d = {}
for line in f:
column = line.split(":")#split name and score
names = column[0]#names in column
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)#name and scores added to end of list
count = count + 1
for names, v in sorted(d.items()):#sorted
average = (sum(v)/len(v))
print(names,average)#average score printed
averages=[]
averages.append(average)
elif viewclass=='2 average':
with open("2.txt") as f:
d = {}
for line in f:
column = line.split(":")
names = column[0]
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)
count = count + 1
for names, v in sorted(d.items()):
average = (sum(v)/len(v))
print(names,average)
averages=[]
averages.append(average)
elif viewclass=='3 average':
with open("3.txt") as f:
d = {}
for line in f:
column = line.split(":")
names = column[0]
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)
count = count + 1
for names, v in sorted(d.items()):
average = (sum(v)/len(v))
print(names,average)
averages=[]
averages.append(average)
我的其他代码可以工作,但是当我运行它的时候信号文件可以工作但是当我选择它时我得到了这个错误
choose a class number and either alphabetically, average or highest?1 average
Traceback (most recent call last):
File "C:/Users//Documents/New folder (2)/14343 - Copy.py", line 10, in <module>
for line in f:
ValueError: I/O operation on closed file.
答案 0 :(得分:1)
with open("3.txt") as f:
d = {}
您正在通过创建字典来完成with函数
完成后,打开的文件为closed
应该如下
with open("2.txt") as f:
d = {}
for line in f:
column = line.split(":")
names = column[0]
scores = int(column[1].strip())
count = 0
while count < 3:
d.setdefault(names, []).append(scores)
count = count + 1
with
被称为context manager
他们在函数启动时打开文件,并在函数完成时关闭文件
您多次犯了同样的错误
实际错误表明您正在阅读已关闭文件对象的内容