1

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.

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked perfectly, also noticed that I need to say str(line) when write the line in due to my values being ints... But that's solved so thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.