如何将得分最高的5位用户和相应的用户附加到外部文件中

时间:2019-01-16 19:05:25

标签: python

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

我想将分数和用户名添加到一个外部文件中,该文件保留在该文件中,以后可以在另一游戏中作为前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'

3 个答案:

答案 0 :(得分:0)

打开文件后,您需要阅读文件内容并追加内容,需要编写。在with语句中,执行以下操作:

file_content = out_file.read()

以及以下内容:

out_file.write("Your output")

答案 1 :(得分:0)

附加到文件

out_file不是列表。您必须使用write()方法来写文件。此外,print(out_file)打印对象表示形式,而不是文件内容。

只需将out_file.append()替换为out_file.write()

score = '11'
gametag = 'Griminal'
with open("scores.txt", "a") as out_file:
    out_string = str(score) + " points from: " + str(gametag) + "\n"
    print(out_string)
    out_file.write(out_string)

排序文件

据我所知,没有简单的方法可以对文件进行排序。也许其他人可以为您建议一个更好的方法,但是我会在列表中读取整个文件(文件的每一行作为列表的元素),对其进行排序,然后再次将其保存在文件中。当然,如果您需要对文件本身进行排序,就可以这样做。如果您的排序仅出于打印目的(即您不在乎文件本身是否已排序),则只需将新分数保存在文件中,然后阅读并让脚本在打印前对输出进行排序。

这是您读取和打印排序结果的方式:

with open("scores.txt", "r") as scores:
    lines = scores.readlines() #reads all the lines

sortedlines = 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
    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
    for i in sortedlines:
        out_file.write(i)

答案 2 :(得分:0)

就像其他人所说的,out_file不是列表,而是一个对象(文件指针),该对象具有访问文件内容的方法,如

out_file.read()

如果您想以列表形式读取文件内容

top_scores = out_file.read().split('\n')

,并继续附加out_file.write()

相关问题