In the previous lesson, we mentioned that consecutive calls to the
write method append text to the end. Here we are going to continue with this topic and learn how to work with files line by line.
How to write text line-by-line
We often have an iterator that provides text line by line. Of course, you can write a loop, but there's a better way — the
writelines method. Here's how it works:
f = open("foo.txt", "w") f.writelines(["cat\n", "dog\n"]) f.close() f = open("foo.txt", "r") print(f.read()) # => cat # => dog f.close()
As you can see, we wrote all the lines in the correct order. This approach is preferable when you need to write a large amount of text that you receive and process line by line. It's possible to accumulate the entire text in a single string beforehand, but it may require much memory. We should write the lines as they become available, and
writelines is perfect.
How to read text line-by-line
You can not only write to a file line by line but also read it in the same way:
f = open("foo.txt") f.readline() # 'cat\n'