1

这是我制作的代码,更多关于它的解释如下。

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 文档的情况下做到这一点?

4

1 回答 1

0

我的,我的,乱七八糟的代码(无意冒犯)......您的主要/当前问题是您在一个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
于 2017-07-11T19:32:59.343 回答