Home > Software engineering >  Writing to file throws TypeError: 'Nonetype' object is not iterable
Writing to file throws TypeError: 'Nonetype' object is not iterable

Time:03-03

A file 'modify.txt' contains three cities:

Mumbai
London
Berlin

When I use the write(), I get the error:

for line in lines:
TypeError: 'NoneType' object is not iterable
file_name = 'modify.txt'
with open(file_name, 'a') as my_modifications:
    lines = my_modifications.write("New York\n")

for line in lines:
    print(f"{line.strip()}")

Similar issue persists when I use integers in the write(), I get 'int' object is not iterable.

My objective is to display the updated output from the text file after executing the write()

CodePudding user response:

As already mentioned in the comments f.write(string) returns the number of characters written. This means that your variable lines is not iterable. That's why you get an error.

First step (write content to the file)

with open("modify.txt", "a") as f:
    f.write("New York\n")

Second step (read each line from the file)

with open("modify.txt", "r") as f:
    for line in f:
        print(line.strip())
  • Related