Working With Multiline Files
00:00 In this lesson, which continues where you left off previously, you’ll learn a few ways of using Python to work with multiline text files. You’re free to use a differently named variable, but in this case, you reuse an existing variable by binding it to a new file object.
Now you can call
.readline() to obtain the first line from the file. Notice that the return line includes a
\n special sequence, which represents the universal newline character. This is a blank line, which has no content other than that line break. When you call
.readline() again, then you’ll get the next line from the file.
The loop will pick up where you left off, and it’ll continue reading the subsequent lines from the file. The extra vertical space between the printed lines is the result of the fact that each line comes with a newline character of its own, while the
print() function also appends a newline by default.
However, if you don’t mind loading the entire file into memory, then another approach you can use is to call the
.readlines() method. That’s plural,
.readlines(), which you shouldn’t confuse with the
.readline() that you’ve already used.
.readlines() method always returns a list, which can potentially be empty if there are no more lines in the file. But when you rewind to the beginning of the file, then it’ll return a list of strings corresponding to the lines in your file.
03:03 The file is open at the beginning, like in the read-only mode, but it doesn’t overwrite the existing content, so you can read it. In this case, there’s only one line, which isn’t actually terminated with a newline character.
Another convenient way of writing text to a file in Python is to call the
print() function. By default, this function prints to the console, but you can optionally redirect it so that it will write to a specified file instead. To do so, you need to pass an extra parameter called
file with a file object as the value.
Become a Member to join the conversation.