Python, read the content of a file
By Flavio Copes
Learn how to read the content of a file in Python using the open() function and the read() and readline() methods, then close the file when you are done.
To read the content of a file in Python, open it with the open() global function, then call read() to get the whole content as a string, or readline() to read it one line at a time.
open() accepts 2 parameters: the file path, and the mode.
To read, use the read (r) mode:
filename = '/Users/flavio/test.txt'
file = open(filename, 'r')
#or
file = open(filename, mode='r')
'r' is also the default, so open(filename) alone does the same thing.
Reading the whole file
Once you have the file open, you can use the read() method to read the entire content of the file into a string:
content = file.read()
This is perfect for small files, like configuration files. For a very large file, a log file for example, it loads everything into memory at once, which you might want to avoid.
Reading one line at a time
You can also choose to read the content one line at a time:
line = file.readline()
Each call returns the next line, including its trailing newline character. When the file is finished, readline() returns an empty string.
It’s common to combine this with a loop, for example to print every line:
filename = '/Users/flavio/test.txt'
file = open(filename, 'r')
while True:
line = file.readline()
if line == '': break
print(line)
Notice one detail: the output has a blank line between each line of the file. That’s because line keeps its own newline, and print() adds another. Use print(line, end='') to avoid the double spacing.
The more idiomatic version of this loop iterates over the file object directly:
for line in file:
print(line, end='')
At the end of your file processing, remember to close the file:
file.close()
Closing the file automatically
Forgetting close() is the classic mistake with this API. If an error happens between open() and close(), the file stays open.
The with statement solves this. It closes the file for you, even if the code inside raises an exception:
with open('/Users/flavio/test.txt', 'r') as file:
content = file.read()
This is the form I recommend for everyday code.
One last thing: if the path doesn’t exist, open() raises a FileNotFoundError. Wrap the call in a try block if the file might legitimately be missing, for example a cache file on the first run of the program.
Related posts about python: