Skip to main content
Practice

How to Read File Contents

In this lesson, we will explore various ways to read files in Python.


Different Methods to Read Files

Three primary methods to read files in Python are read(), readline(), and readlines().

Each method retrieves the file contents in slightly different ways.


Reading the Entire File at Once with read()

The read() method, which we briefly introduced in the previous lesson, reads the entire file content as a single string.

It's commonly used when the file is relatively small and the contents need to be processed all at once.

Reading the Entire File
with open("example_file.txt", "r") as file:
# Read the entire content of the file into a string
content = file.read()

# Print the file content
print(content)

In the code above, the entire content of the "example_file.txt" file is stored in the content variable, and then printed.

The entire content of the file is returned as a string.


Reading the File Line by Line with readline()

The readline() method reads the file content line by line, including the newline character (\n).

It is typically used for processing each line sequentially, especially when dealing with large files.

Reading File Line by Line
# example_file.txt content:
# Hello!
# Welcome to
# Python

with open("example_file.txt", "r") as file:
# Read the first line and store it in the variable line (including newline character)
line = file.readline()

# Loop until the end of the file
while line:
# Print each line (newline character is included, so use end="" to avoid extra newline)
print(line, end="")
# Read the next line
line = file.readline()

# Output:
# Hello!
# Welcome to
# Python

In the code example above, the content of a multi-line text file is read from the top line by line, stored in the line variable, and then printed.

When readline() reaches the end of the file, it returns an empty string ''.

If line is assigned an empty string, while line: will evaluate to False, indicating that the end of the file has been reached.


Reading All Lines as a List with readlines()

The readlines() method reads all lines of the file and returns them as a list.

Since each line is stored as an element of the list, it makes processing individual lines convenient.

Reading Multiple Lines Into a List
# example_file.txt content:
# Hello!
# Welcome to
# Python

with open("example_file.txt", "r") as file:
# The value of lines: ['Hello!\n', 'Welcome to\n', 'Python\n']
lines = file.readlines()

# Iterate over each element of the list and print it
for line in lines:
# Print each line (newline character is included, so use end="" to avoid extra newline)
print(line, end="")

readlines() stores each line of the file as an element of a list.

By iterating over each element of the list, all file contents can be printed at once.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.