【问题标题】:Python: Write array values into filePython:将数组值写入文件
【发布时间】:2015-07-07 06:17:55
【问题描述】:

我正在编写一个 python 项目,其中涉及我读取文件并用文件中的整数值填充数组,执行整个疯狂的不重要的过程(井字游戏),然后在最后添加一个数字(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' object is not iterable.

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

【问题讨论】:

    标签: python arrays file append


    【解决方案1】:

    for 循环将要求 i 迭代可迭代对象的值,并且您提供的是单个 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
    

    【讨论】:

    • 谢谢,效果很好,还注意到由于我的值是整数,所以在写行时我需要说 str(line) ......但这已经解决了,谢谢!
    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2018-11-21
    • 2011-10-26
    相关资源
    最近更新 更多