我如何附加到一个外部文件与前5名的分数和各自的美国

2024-06-06 17:51:51 发布

您现在位置: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\文件)时,它会被打印到shell中

所以我不能将新的分数添加到列表中并保存到文件中。有人能解决这些问题吗?你知道吗

要排序,我有代码:

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'

Tags: 文件代码iotxt列表stringout分数
3条回答

附加到文件

out_file不是列表。必须使用write()方法在文件上写入。同时print(out_file)打印对象表示,而不是文件的内容。你知道吗

out_file.write()代替out_file.append()

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)

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

out_file.read()

如果您想以列表的形式读入文件的内容,可以这样做

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

并继续用out_file.write()附加到它后面

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

file_content = out_file.read()

并附上以下内容:

out_file.write("Your output")

相关问题 更多 >