Python:将数组值写入fi

2024-04-26 22:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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 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(highscores):。我得到“TypeError:”int“对象不可iterable。

我只想知道我是否在正确的轨道上,以及如何解决这个问题。我还想指出,我读写的这些值需要是整数类型,而不是字符串类型,因为在将新值写回文件之前,我可能需要将其排序到现有数组中。

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


Tags: 文件代码infromforcloseline整数
1条回答
网友
1楼 · 发布于 2024-04-26 22:57:26

for循环将要求我迭代iterable的值,而您提供的是单个int而不是iterable对象 你应该迭代range(0,len(highscores))

for i in (0,len(highscores))

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

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

相关问题 更多 >