Python:将数组值写入文件
我正在编写一个python项目,其中包括读取一个文件并用文件中的整数值填充一个数组,执行一个完全不重要的过程(tic-tac-toe游戏),然后在最后向数组中添加一个数字(wins)并将其打印回文件 以下是我的文件读取代码:Python:将数组值写入文件,python,arrays,file,append,Python,Arrays,File,Append,我正在编写一个python项目,其中包括读取一个文件并用文件中的整数值填充一个数组,执行一个完全不重要的过程(tic-tac-toe游戏),然后在最后向数组中添加一个数字(wins)并将其打印回文件 以下是我的文件读取代码: highscores = [] #Read values from file and put them into array file = open('highscore.txt', 'r') #read from file file.readline() #read he
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):') #write heading line
for i in len(highscores):
file.write(highscores[i])
file.close() #close file
目前,我的整个程序一直在运行,直到我读到文件编写代码中的行:for I in len(高分):
。我得到'TypeError:'int'对象不可编辑
我只是想知道我是否在正确的轨道上,以及如何解决这个问题。我还想指出,我读写的这些值需要是整数类型,而不是字符串类型,因为我可能需要在将新值写回文件之前将其排序到现有数组中。for循环将要求我迭代iterable的值,您提供的是单个
int
对象,而不是iterable
对象
您应该迭代范围(0,len(高分))
:
或者更好,直接在数组上迭代
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
for
循环将要求i对iterable的值进行迭代,您将提供一个int
而不是iterable
对象
您应该迭代范围(0,len(高分))
:
或者更好,直接在数组上迭代
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
谢谢,这工作得很好,还注意到我需要说str(行)时写的行,因为我的价值观是整数。。。但问题解决了,谢谢你!谢谢,这工作得很好,还注意到我需要说str(行)时写的行,因为我的价值观是整数。。。但问题解决了,谢谢你!