Python provides several methods for reading data from a file.
The most commonly used methods are read(),
readline(), and readlines().
with open() when possible. It automatically closes
the file after the block finishes.
To read an existing text file, open it using r mode.
file = open("data.txt", "r")
print(file.read())
file.close()
The r mode means read mode.
The recommended approach is to use the with statement.
with open("data.txt", "r") as file:
data = file.read()
print(data)
The file is automatically closed when the with block ends.
The read() method reads the contents of a file and returns
them as a string for a text file.
Suppose data.txt contains:
Hello Python
Welcome to File Handling
Python code:
with open("data.txt", "r") as file:
content = file.read()
print(content)
You can pass a number to read() to read up to that many
characters from the current file position.
with open("data.txt", "r") as file:
content = file.read(5)
print(content)
If the file starts with Hello Python, the output is:
The file position moves forward as data is read.
with open("data.txt", "r") as file:
print(file.read(5))
print(file.read())
The first read(5) consumes up to five characters.
The second read() reads from the current position to the end.
The readline() method reads one line at a time.
with open("data.txt", "r") as file:
line = file.readline()
print(line)
If the file contains:
Python
Java
JavaScript
The first call to readline() reads the first line.
Calling readline() repeatedly reads the next line each time.
with open("data.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)
The readlines() method reads all lines and returns them
as a list.
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
A file object can be iterated over directly.
with open("data.txt", "r") as file:
for line in file:
print(line)
This processes the file one line at a time.
Lines read from a text file often contain a newline character.
The strip() method can remove surrounding whitespace.
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
This is useful when you want to print each line without the extra newline or surrounding whitespace.
When reading text files, you can specify the encoding explicitly.
with open(
"data.txt",
"r",
encoding="utf-8"
) as file:
content = file.read()
print(content)
UTF-8 is a widely used encoding for text.
If a file has no more data to read, read() returns an empty
string.
with open("data.txt", "r") as file:
data = file.read()
if data == "":
print("File is empty")
else:
print(data)
The tell() method returns the current position in the file.
with open("data.txt", "r") as file:
print(file.tell())
file.read(5)
print(file.tell())
The exact position depends on the file content and text stream.
The seek() method changes the current file position.
with open("data.txt", "r") as file:
file.read(5)
file.seek(0)
content = file.read()
print(content)
Here, seek(0) moves the position back to the beginning.
One simple way to access a specific line is to read the lines into a list.
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines[1])
List indexing starts from 0, so lines[1]
represents the second line.
with open("data.txt", "r") as file:
lines = [
line.strip()
for line in file
]
print(lines)
For large files, reading the entire file at once may use a lot of memory. Processing the file line by line is often more appropriate.
with open("largefile.txt", "r") as file:
for line in file:
process = line.strip()
print(process)
This approach processes one line at a time.
Binary files should be opened using a binary mode such as rb.
with open("image.jpg", "rb") as file:
data = file.read()
print(len(data))
The result of reading binary data is a bytes object.
If the requested file does not exist, opening it in read mode raises
FileNotFoundError.
try:
with open("student.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("Student file not found")
Suppose student.txt contains:
Name: Rahul
Course: Python
Age: 21
Python code:
with open("student.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
count = 0
with open("data.txt", "r") as file:
for line in file:
count += 1
print("Total lines:", count)
The variable count keeps track of the number of lines read.
with open("data.txt", "r") as file:
content = file.read()
words = content.split()
print("Total words:", len(words))
The split() method separates the text into words using
whitespace by default.
with open("message.txt", "r", encoding="utf-8") as file:
message = file.read()
print("Message:", message)
The complete file content is stored in the message variable.
| Method | Purpose |
|---|---|
read() |
Reads the file content or a specified number of characters. |
readline() |
Reads one line at a time. |
readlines() |
Reads lines and returns them as a list. |
open() to open a file.r mode to read a file.read() reads file content.readline() reads one line at a time.readlines() returns file lines as a list.for loop.strip() can remove surrounding whitespace from a line.tell() returns the current file position.seek() changes the file position.encoding="utf-8" when appropriate for text files.rb when reading binary files.with open() to automatically close the file.Question: Which method reads one line from a file?