Barry Michael Doyle
Barry Michael Doyle

Reputation: 10608

Python: Write array values into file

I'm coding a python project that involves me reading a file and filling an array with the integer values in the file, doing a whole crazy none important process (tic tac toe game) and then at the end, adding a number (wins) to the array and print it back out to the file.

Here's my file reading code:

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

And here's my file writing code:

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

Currently my whole program runs until I read the line: for i in len(highscores): in my file writing code. I get 'TypeError: 'int' object is not iterable.

I just want to know if I'm on the right track and how to solve this issue. I also want to note that these values that I read and write need to be integer types and not string types because I may need to sort the new value into the existing array before writing it back to the file.

Upvotes: 1

Views: 19488

Answers (1)

Bruce
Bruce

Reputation: 7132

The for loop will ask i to iterate over the values of an iterable, and you're providing a single int instead of an iterable object You should iterate over range(0,len(highscores)):

for i in (0,len(highscores))

or better, iterate directly over the array

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

Upvotes: 7

Related Questions