Read Data from a File
Now that we have created and written to book.txt, let's learn how to read its content. Python offers several methods for reading files. We will explore the most common ones.
We will continue working with the file_io.py script. You will add code to read the file you just created.
The read() Method
The read() method reads the entire content of a file and returns it as a single string.
Append the following code to the end of your file_io.py script. This will make the script first write the file, and then read it back and print its content.
## The writing code from the previous step should be above this
print("\n--- Reading entire file with read() ---")
with open("book.txt", "r") as f:
content = f.read()
print(content)
Save the file and run it from the terminal:
python ~/project/file_io.py
The output will now include the content of book.txt printed to the console:
--- Reading entire file with read() ---
Bed before bright moonlight,
Suspected to be frost on the ground.
Head held high, gazing at the bright moon,
Head bowed low, thinking of my homeland.
Iterating Over Lines
A more memory-efficient way to read a file, especially a large one, is to process it line by line. You can do this by iterating directly over the file object in a for loop.
Now, append this next block of code to file_io.py:
print("\n--- Reading file line by line ---")
with open("book.txt", "r") as f:
for line in f:
print(line, end='')
Here, end='' in the print() function prevents it from adding an extra newline, since each line read from the file already ends with a newline character (\n).
Save and run the script again:
python ~/project/file_io.py
The output for this section will be identical to the read() method's output, but the underlying process is different, reading one line at a time.
The readlines() Method
The readlines() method reads all lines from a file and returns them as a list of strings.
Finally, append this last block of code to file_io.py:
print("\n\n--- Reading all lines with readlines() ---")
with open("book.txt", "r") as f:
all_lines = f.readlines()
print(all_lines)
Save and run the script one last time:
python ~/project/file_io.py
The output for this section will be a Python list, where each element is a string representing a line from the file:
--- Reading all lines with readlines() ---
['Bed before bright moonlight,\n', 'Suspected to be frost on the ground.\n', 'Head held high, gazing at the bright moon,\n', 'Head bowed low, thinking of my homeland.']
You have now practiced the fundamental methods for both writing to and reading from files in Python.