Python:将值读入空数组,然后返回文件

时间:2015-04-28 12:50:43

标签: python arrays sorting file-io

我想从python中的txt文件(highscore.txt)中读取数字,并将这些值分配给空数组(高分)。

然后我想在数组中添加另一个值,然后用数组中的新值覆盖该文件。

我已经整理了一个程序,但它没有给我所需的输出。请看看它有什么问题......

从文件中读取:

highscores = []
#Read values from file and put them into array
file = open('highscore.txt', 'r') #read from file
file.readline() #read heading line
for line in file:
    highscores.append(file.readline())
file.close() #close file 

添加值并覆盖文件:

highscores.append(wins)
# Print sorted highscores print to file
file = open('highscore.txt', 'w') #write to file
file.write('Highscores (number of wins out of 10 games):\n') #write heading line
for line in highscores:
    file.write(str(line))
file.close() #close file

它需要以这样的方式工作(一旦这个工作)在重新覆盖文件之前用添加的值对数组进行排序......

我希望从文件中读取:

Highscores (number of wins out of 10 games):
8
6
5
5
3
1
0
0

将这些值读入数组 然后向数组添加(假设)4 然后用新值覆盖文件

在这种情况下,我们可以预期输出为:

Highscores (number of wins out of 10):
8
6
5
5
3
1
0
0
4

希望你能找出那里的错误...

编辑:感谢EvenListe的回答,我可以找到一个解决方案,这里是我用来使我的程序完美运行的相关代码(包括添加的数组在添加后按降序排序)

from __future__ import print_function

highscores = []
with open("highscore.txt", "r") as f:
    f.readline() # Reads header
    for line in f:
        highscores.append(line.strip())

highscores.append(wins)
highscores = sorted(highscores, key=int, reverse=True)
# Print sorted highscores print to file
with open("highscore.txt", "w") as f:
  for val in highscores:
    print(val, file=f)

如果你想测试文件中的行是什么,你可以使用它(我在添加数组之前使用它,在添加数组之后,它确实有助于找出错误而不必不断打开文件):

print('Highscores (number of wins out of 10 games):')
for lines in highscores:
    print(lines)

2 个答案:

答案 0 :(得分:2)

据我所知,你的代码的一个明显问题是你的

for line in infile:
    highscores.append(infile.readline())

跳过其他每一行。你应该

for line in infile:
    highscores.append(line)

或更容易:

highscores=infile.readlines()
highscores=highscores[1:]  #Remove header

答案 1 :(得分:1)

很难在没有看到预期结果与实际结果的情况下判断出什么是错误的,但我的猜测是你需要从你读过的行中删除\n

from __future__ import print_function
highscores = []
with open("highscore.txt", "r") as f:
  for line in f:
    highscores.append(line.strip())

highscores.append(wins)
with open("highscore.txt", "w") as f:
  for val in highscores:
    print(val, file=f)