这是我制作的代码,更多关于它的解释如下。
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.
这是我编写的代码,任务是:
算法
告诉他们准备好后按 Enter 键
以秒(和分钟)为单位获取第一次
让他们输入字母并按 Enter
以秒为单位获取第二次(和分钟)
检查他们是否正确输入了字母
如果他们输入正确然后
从第二次减去第一次
告诉他们他们花了多少秒
扩展
记录所达到的最佳时间。<-----这是我卡住的地方
处理输入的大写或小写字母<-----我可以这样做,我只是还没有包含它
编辑:是否有另一种方法可以在不使用 txt 文档的情况下做到这一点?