Recapping Text File Operations
In this lesson, you’ll get a quick summary of what you’ve just learned about reading and writing text files in Python. When you open a file in Python in a mode that enables reading, such as the read-only mode denoted with the letter code
r, you can read the file in the following few ways. First, you can load the entire file’s contents at once into a Python string by calling the file object’s
.read() method. However, this is only recommended for smaller files.
Alternatively, you can read the next line until reaching a line ending in the file. Note that this will include the trailing newline character, which you can remove by calling the string’s
You can also read all lines at once and put them into a Python list, which may sometimes be empty if there are no more lines in the file. Finally, you can iterate over the file object line by line, which might be useful if the file doesn’t have a known size or is too big to fit in the memory. This is similar to manually calling the
.readline() method in a loop.
When you open the file in a mode that allows for writing new content to it, then you also have a few choices. Specifically, you can write a piece of text to the file by calling the
.write() method with a Python string as an argument. However, you have to remember to append the
\n special sequence at the end of the string to terminate the line.
Finally, you can also call the
print() function with an optional
file argument bound to the file object you want to write to. In this case, the extra newline character appended by each call to the
print() function is quite convenient.
Reading and writing text files in Python isn’t terribly difficult once you master the basics. However, when you start dealing with actual files in real life, then you’ll quickly notice that it can get a bit tedious. Therefore, at some point, you might consider using a higher-level abstraction that hides the implementation details of reading and writing text files formatted in some specific way, like CSV, or comma-separated values. In the next lesson, you’ll use Python’s built-in
csv module to read tabular data, which you could have exported from a database or a spreadsheet program, for example.
Become a Member to join the conversation.