如何附加到具有前 5 名分数和相应用户的外部文件

我在这段代码中遇到了很多问题,但我再次难倒如何做到这一点。


我想将分数和用户名添加到一个外部文件中,该文件保留在该文件中,以后可以在另一场比赛中作为前 5 名分数和获得它们的人访问。到目前为止,我已经得到了这个:


score = '11'

gametag = 'Griminal'

with open("scores.txt", "a+") as out_file:

    print(out_file)

    out_string = ""

    out_string += str(score) + " points from: " + str(gametag)

    out_string += "\n"

    print(out_string)

    out_file.append(out_string)

    print(out_file)

但是,正如我注意到的那样,该文件没有作为列表打开,而是作为:


<_io.TextIOWrapper name='scores.txt' mode='a+' encoding='cp1252'>

当我运行 print(out_file) 时,它会被打印到外壳中


所以我无法将新分数附加到列表中并将其保存到文件中。有没有人有解决这些问题的方法?


要对其进行排序,我有以下代码:


f = sorted(scores, key=lambda x: x[1], reverse=True)

top5 = f[:5]

print(top5)

据我所知,这有效。


我收到的错误代码是:


Traceback (most recent call last):

  File "C:/Users/gemma/OneDrive/Desktop/Gcse coursework.py", line 60, in 

<module>

    out_file.append(out_string)

AttributeError: '_io.TextIOWrapper' object has no attribute 'append'


慕后森
浏览 152回答 3
3回答

UYOU

附加到文件out_file不是一个列表。您必须使用该write()方法写入文件。还print(out_file)打印对象表示,而不是文件的内容。只需替换out_file.append()为out_file.write():score = '11'gametag = 'Griminal'with open("scores.txt", "a") as out_file:&nbsp; &nbsp; out_string = str(score) + " points from: " + str(gametag) + "\n"&nbsp; &nbsp; print(out_string)&nbsp; &nbsp; out_file.write(out_string)对文件进行排序据我所知,没有简单的方法可以对文件进行适当的排序。也许其他人可以为您提供更好的方法,但我会读取列表中的整个文件(文件的每一行作为列表的一个元素),对其进行排序,然后再次将其保存在文件中。这当然,如果您需要对文件本身进行排序。如果您的排序仅用于打印目的(即您不关心文件本身是否已排序),那么只需将新分数保存在文件中,然后读取它并让脚本在打印前对输出进行排序。这是读取和打印排序结果的方法:with open("scores.txt", "r") as scores:&nbsp; &nbsp; lines = scores.readlines() #reads all the linessortedlines = sorted(lines, key=lambda x: int(x.split()[0]), reverse=True) #be sure of the index on which to sort!for i in sortedlines[:5]: #the first 5 only&nbsp; &nbsp; print(i)x.split()将每一行拆分为一个单词列表,使用空格作为分隔符。这里我使用索引 0,因为在前一个输入之后out_string = str(score) + " points from: " + str(gametag) + "\n",分数位于列表的第一个元素中。如果您需要再次保存文件,您可以sortedlines在其中写入 覆盖它。with open("scores.txt", "w") as out_file: #mode "w" deletes any previous content&nbsp; &nbsp; for i in sortedlines:&nbsp; &nbsp; &nbsp; &nbsp; out_file.write(i)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python