List ValueError:将结果添加到txt文档时,返回对已关闭文件的I/O操作
这是我编写的一个代码,下面将详细解释List ValueError:将结果添加到txt文档时,返回对已关闭文件的I/O操作,list,python-3.x,index-error,List,Python 3.x,Index Error,这是我编写的一个代码,下面将详细解释 import os.path if os.path.isfile('Times.txt'): #checks if Times file exists file = open('Times.txt','r+') #Opens file to read if it does with open('Times.txt','r+') as f: mylist = f.read().splitlines()
import os.path
if os.path.isfile('Times.txt'): #checks if Times file exists
file = open('Times.txt','r+') #Opens file to read if it does
with open('Times.txt','r+') as f:
mylist = f.read().splitlines()
mylist=[int(x) for x in mylist]
mylist.sort()
if sum(mylist)!=0:
print('Highscore:',mylist[-1],'seconds')
else:
file = open('Times.txt','w') #Creates file if Times.txt does not exist
print("Type the alphabet as fast as you can!") #Game code- User types the alphabet as fast as they can.
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print("GO!!")
start = time.time()
alph=""
while alph != "abcdefghijklmnopqrstuvwxyz":
alph=input("")
if alph != "abcdefghijklmnopqrstuvwxyz":
print("INCORRECT ALPHABET, TRY AGAIN!")
end = time.time()
timetaken=(end - start)//1
Seconds=timetaken
mins=0
while timetaken >= 60:
timetaken=timetaken-60
mins=mins+1
Time = (mins,"minutes and",timetaken,"seconds")
print('You took',Time)
f.write(str(Seconds)) #Adds time to text file
当我运行代码时,它返回以下错误:
Traceback (most recent call last):
File "C:\Users\johnson.427\Desktop\Adam - Copy\Documents\Adam Homework\SWCHS\YEAR 9\Computing\challenge.py", line 104, in <module>
c7()
File "C:\Users\johnson.427\Desktop\Adam - Copy\Documents\Adam Homework\SWCHS\YEAR 9\Computing\challenge.py", line 102, in c7
f.write(str(Seconds))
ValueError: I/O operation on closed file.
回溯(最近一次呼叫最后一次):
文件“C:\Users\johnson.427\Desktop\Adam-Copy\Documents\Adam-homotation\SWCHS\YEAR 9\Computing\challenge.py”,第104行,在
c7()
文件“C:\Users\johnson.427\Desktop\Adam-Copy\Documents\Adam combiness\SWCHS\YEAR 9\Computing\challenge.py”,第102行,在c7中
f、 写入(str(秒))
ValueError:对关闭的文件执行I/O操作。
这是我编写的代码,任务是:算法
告诉他们准备好后按回车键
以秒(和分钟)为单位获取第一次时间
让他们输入字母表,然后按enter键
以秒(和分钟)为单位获取第二次时间
检查他们是否正确输入了字母表
如果输入正确,则
从第二次减去第一次
告诉他们花了多少秒
扩展
记录达到的最佳时间 我的,我的,多么混乱的代码(无意冒犯)。。。您的主要/当前问题是,您在
with
块中打开文件,因此当您退出with
块时,它会立即关闭文件句柄-当您尝试写入关闭的文件句柄时,最终会出现所显示的错误
首先,不管怎么说,没有必要让你的高分文件保持一个文件句柄的打开状态——当你开始“游戏”时打开并读取它,当你想保存分数时打开并写入它就足够了。因此,所有这些都可以大大简化为:
import os.path
import time
hiscore = 0 # define our hiscore as 0 in case we want to use it somewhere else
if os.path.isfile('Times.txt'): # checks if Times.exe file exists
with open("Times.txt", "r") as f: # open the file for reading
hiscore = int(f.readline().strip()) # read the first line, we'll keep it sorted
print('Highscore: {} seconds'.format(hiscore))
print("Type the alphabet as fast as you can!")
for line in ("3", "2", "1", "GO!!"): # we can iterate-print instead of typing everything...
time.sleep(1)
print(line)
start = time.time() # keep in mind that on Windows time.clock() is more precise!
while True:
if input("") == "abcdefghijklmnopqrstuvwxyz": # on Python 2.x use raw_input instead
break
print("INCORRECT ALPHABET, TRY AGAIN!")
end = time.time()
delta_time = int(end - start)
minutes, seconds = delta_time // 60, delta_time % 60
print("You took {} minutes and {} seconds".format(minutes, seconds))
# and now finally write the delta_time to the Times.txt
with open("Times.txt", "a+") as f: # open Times.txt in read/write mode
scores = {int(line.strip()) for line in f} # read all the lines and convert them to ints
scores.add(delta_time) # add our current score
f.seek(0) # move to the beginning of the file
f.truncate() # truncate the rest
f.write("\n".join(str(x) for x in sorted(scores))) # write the sorted hiscores
我的,我的,多么混乱的代码(无意冒犯)。。。您的主要/当前问题是,您在
with
块中打开文件,因此当您退出with
块时,它会立即关闭文件句柄-当您尝试写入关闭的文件句柄时,最终会出现所显示的错误
首先,不管怎么说,没有必要让你的高分文件保持一个文件句柄的打开状态——当你开始“游戏”时打开并读取它,当你想保存分数时打开并写入它就足够了。因此,所有这些都可以大大简化为:
import os.path
import time
hiscore = 0 # define our hiscore as 0 in case we want to use it somewhere else
if os.path.isfile('Times.txt'): # checks if Times.exe file exists
with open("Times.txt", "r") as f: # open the file for reading
hiscore = int(f.readline().strip()) # read the first line, we'll keep it sorted
print('Highscore: {} seconds'.format(hiscore))
print("Type the alphabet as fast as you can!")
for line in ("3", "2", "1", "GO!!"): # we can iterate-print instead of typing everything...
time.sleep(1)
print(line)
start = time.time() # keep in mind that on Windows time.clock() is more precise!
while True:
if input("") == "abcdefghijklmnopqrstuvwxyz": # on Python 2.x use raw_input instead
break
print("INCORRECT ALPHABET, TRY AGAIN!")
end = time.time()
delta_time = int(end - start)
minutes, seconds = delta_time // 60, delta_time % 60
print("You took {} minutes and {} seconds".format(minutes, seconds))
# and now finally write the delta_time to the Times.txt
with open("Times.txt", "a+") as f: # open Times.txt in read/write mode
scores = {int(line.strip()) for line in f} # read all the lines and convert them to ints
scores.add(delta_time) # add our current score
f.seek(0) # move to the beginning of the file
f.truncate() # truncate the rest
f.write("\n".join(str(x) for x in sorted(scores))) # write the sorted hiscores
我认为这可能是因为如果您是第一次这样做,列表中将没有任何项目,但我不知道如何修复它。另外,是否有其他人可以通知我任何其他会阻止代码正常运行的明显错误?请添加一个非常高时间的默认高分。这将防止文件中没有任何内容。此外,当您写入时,您需要添加一个\n,否则它将不会转到下一行。错误表示您正在尝试写入尚未打开以进行写入的文件;在写入文件之前,您需要
打开该文件:使用open('Times.txt','wb')作为f:f.write(str(Seconds))#将时间添加到文本文件中
我认为这可能是因为如果您第一次这样做,列表中将没有项目,但我不知道如何修复它,其他人能通知我任何其他会阻止代码正常运行的明显错误吗?添加一个默认高分“真的很高的时间”。这将防止文件中没有任何内容。此外,当您写入时,您需要添加一个\n,否则它将不会转到下一行。错误表示您正在尝试写入尚未打开以进行写入的文件;在写入文件之前,您需要打开该文件:将open('Times.txt','wb')作为f:f.write(str(Seconds))#将时间添加到文本文件中
对不起,我是pythoni的新手,如果是这样的话helps@AJ123-您正在尝试手动编辑文件吗?如果Times.txt
文件中的第一行不是一个数字(即在您的情况下是一个空行),它将失败。上面的代码不会产生任何空行,但是如果你手动添加它们,任何事情都会发生helps@AJ123-您正在尝试手动编辑文件吗?如果Times.txt
文件中的第一行不是一个数字(即在您的情况下是一个空行),它将失败。上面的代码不会生成任何空行,但是如果您手动添加它们,则会出现任何问题。