Read the Contents of a File Using Python
In Python, we can read the contents of a file using the built-in open()
function. This function allows us to access and process the file data in different modes, such as reading the entire file, reading line by line, or reading specific bytes.
In this tutorial, we will explore multiple ways to read files in Python with examples.
Examples
1. Reading an Entire File Using read()
The read()
method reads the entire contents of a file as a string.
In this example, we will read the contents of a text file named sample.txt using the read method of file object.

main.py
# Open the file in read mode
with open("sample.txt", "r") as file:
content = file.read()
# Print the contents of the file
print(content)
Explanation:
open("sample.txt", "r")
: Opens the file in read mode.file.read()
: Reads the entire content of the file and stores it in thecontent
variable.with
statement: Ensures the file is properly closed after reading.
Output:

2. Reading a File Line by Line Using readline()
The readline()
method reads a single line from the file at a time.

main.py
# Open the file in read mode
with open("sample.txt", "r") as file:
first_line = file.readline()
second_line = file.readline()
# Print the first two lines
print('Line 1:', first_line, end="")
print('Line 2:', second_line, end="")
Explanation:
file.readline()
: Reads one line at a time from the file.- The first call reads the first line, and the second call reads the second line.
- The
end=""
parameter prevents extra new lines when printing.
Output:

3. Reading a File as a List Using readlines()
The readlines()
method reads all lines from the file and returns them as a list of strings.

main.py
# Open the file in read mode
with open("sample.txt", "r") as file:
lines = file.readlines()
# Print the list of lines
print(lines)
Explanation:
file.readlines()
: Reads all lines from the file and stores them as a list.- Each element in the list represents a line from the file, including the newline character.
Output:

4. Using a Loop to Read a File Line by Line
We can use a loop to read the file line by line efficiently.

main.py
# Open the file in read mode
with open("sample.txt", "r") as file:
for line in file:
print(line, end="")
Explanation:
- The file object itself is an iterable, allowing us to loop through lines directly.
- The
for
loop reads one line at a time and prints it.
Output:

Conclusion
Python provides multiple ways to read the contents of a file:
read()
: Reads the entire file as a string.readline()
: Reads one line at a time.readlines()
: Reads all lines and returns them as a list.- Using a loop: Iterates over the file object line by line efficiently.