Python:将数组值写入文件

Bar*_*yle 0 python arrays file append

我正在编写一个python项目,它涉及我读取一个文件并用文件中的整数值填充一个数组,做一个完全疯狂的非重要过程(tic tac toe game)然后在最后添加一个数字(wins)到数组并将其打印回文件.

这是我的文件阅读代码:

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
Run Code Online (Sandbox Code Playgroud)

这是我的文件编写代码:

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):') #write heading line
for i in len(highscores):
    file.write(highscores[i])
file.close() #close file
Run Code Online (Sandbox Code Playgroud)

目前我的整个程序一直运行,直到我读到这一行:for i in len(highscores):在我的文件中编写代码.我得到'TypeError:'int'对象不可迭代.

我只是想知道我是否走在正确的轨道上以及如何解决这个问题.我还想要注意,我读取和写入的这些值需要是整数类型而不是字符串类型,因为我可能需要在将新值写入现有数组之前将其写回文件.

我通常不会使用python,所以请原谅我缺乏经验.提前感谢您的帮助!:)

Bru*_*uce 6

for循环会问我来遍历一个可迭代的值,而你提供一个单一的int,而不是一个iterable对象,您应该遍历range(0,len(highscores)):

for i in (0,len(highscores))
Run Code Online (Sandbox Code Playgroud)

或者更好,直接在数组上迭代

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):') 
for line in highscores:
     file.write(line)
file.close() #close file
Run Code Online (Sandbox Code Playgroud)