Files are one of the most common sources of data in Python applications. Whether you are building a web application, analyzing datasets, generating reports, or processing logs, your program often needs to read information stored in files. Python provides several simple yet powerful methods for reading files efficiently.
Reading files allows a program to retrieve previously stored information instead of asking users to enter the same data repeatedly. It is an essential skill for data analysis, machine learning, automation, web development, and software engineering.
In this lesson, you will learn how to open files in read mode, understand file objects, read entire files or specific portions of a file, and explore practical examples that demonstrate real-world file reading techniques.
After completing this lesson, you will be able to:
Most applications work with information that already exists. Instead of manually entering data every time, programs simply read stored files.
Common examples include:
Before reading data, the file must be opened using the open() function.
file = open("filename.txt", "r")
The r mode stands for read mode. If the file does not exist, Python raises a FileNotFoundError.
file = open("student.txt", "r")
print(file)
file.close()
Output
<_io.TextIOWrapper name='student.txt' mode='r' encoding='UTF-8'>
The output shows that Python has successfully opened the file and created a file object.
When Python opens a file, it creates a file object. This object provides methods such as read(), readline(), and readlines() for working with the file.
A file object also stores useful information such as the file name, mode, and current reading position.
file = open("student.txt", "r")
print(file.name)
print(file.mode)
file.close()
Output
student.txt
r
read()The read() method reads the complete contents of a file and returns them as a string.
Suppose student.txt contains:
Rahul
Python
92
file = open("student.txt", "r")
content = file.read()
print(content)
file.close()
Output
Rahul
Python
92
This method is convenient for small files because it loads the complete file into memory.
You can pass a number to read() to read only a specific number of characters.
file = open("student.txt", "r")
print(file.read(5))
file.close()
Output
Rahul
Only the first five characters are read from the file.
file = open("student.txt", "r")
print(file.read(5))
print(file.read(8))
file.close()
Output
Rahul
Python
Notice that the second read() starts where the first one ended because the file pointer automatically moves forward.
| Application | Purpose |
|---|---|
| School Software | Read student records. |
| Hospital System | Retrieve patient information. |
| Banking Application | Read transaction history. |
| Data Analytics | Load CSV and text datasets. |
| Machine Learning | Load training data. |
| Web Applications | Read configuration files. |
Suppose the file employees.txt contains:
Neha
HR
50000
Python program:
file = open("employees.txt", "r")
employee = file.read()
print(employee)
file.close()
Output
Neha
HR
50000
Consider the following program.
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()
Execution Steps
read() method retrieves all file contents.content.Output
Contents of sample.txt
read() on very large files.read() always starts from the beginning after multiple calls.In this section, you learned why reading files is important, how to open files in read mode, understand file objects, read an entire file, and read a specific number of characters using the read() method. You also explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn how to read files line by line using readline(), retrieve all lines using readlines(), iterate through files using a for loop, and compare the different file reading methods.
In the previous section, you learned how to open files in read mode, understand file objects, and read the complete contents of a file using the read() method. While read() is useful for small files, Python also provides other methods that allow you to read one line at a time or retrieve all lines as a list. These methods are especially useful when working with large files or structured text data.
In this section, you will learn how to use readline(), readlines(), and for loops to read files efficiently. You will also compare these methods and understand when each one should be used.
readline()The readline() method reads one line from a file each time it is called.
file.readline()
Suppose student.txt contains:
Rahul
Python
92
file = open("student.txt", "r")
print(file.readline())
print(file.readline())
print(file.readline())
file.close()
Output
Rahul
Python
92
Each call to readline() moves the file pointer to the next line.
file = open("student.txt", "r")
first_line = file.readline()
print(first_line)
file.close()
Output
Rahul
This approach is useful when only the first line of a file is required.
readlines()The readlines() method reads the complete file and returns all lines as a list.
file = open("student.txt", "r")
lines = file.readlines()
print(lines)
file.close()
Output
['Rahul\n', 'Python\n', '92']
Each element in the list represents one line of the file.
file = open("student.txt", "r")
lines = file.readlines()
print(lines[0])
print(lines[1])
file.close()
Output
Rahul
Python
for LoopUsing a for loop is one of the most efficient ways to read files, especially when the file contains thousands of lines.
file = open("student.txt", "r")
for line in file:
print(line)
file.close()
Output
Rahul
Python
92
Each line usually contains a newline character (\n). The strip() method removes it.
file = open("student.txt", "r")
for line in file:
print(line.strip())
file.close()
Output
Rahul
Python
92
| Method | Description | Best Used For |
|---|---|---|
read() |
Reads the entire file. | Small files. |
readline() |
Reads one line at a time. | Reading specific lines. |
readlines() |
Returns all lines as a list. | Processing all lines as a list. |
for Loop |
Reads one line at a time automatically. | Large files. |
Suppose employees.txt contains:
Neha
Rahul
Priya
file = open("employees.txt", "r")
for employee in file:
print(employee.strip())
file.close()
Output
Neha
Rahul
Priya
file = open("log.txt", "r")
logs = file.readlines()
print("Total Lines:", len(logs))
file.close()
Output
Total Lines: 25
file = open("student.txt", "r")
print(file.readline().strip())
print(file.readline().strip())
file.close()
Output
Rahul
Python
read() only for small files.for loop for large files.strip() to remove newline characters.Consider the following program.
file = open("student.txt", "r")
for line in file:
print(line.strip())
file.close()
Execution Steps
for loop reads one line at a time.strip() method removes newline characters.Output
Rahul
Python
92
read() for very large files.readlines() returns a string instead of a list.readline() repeatedly without understanding that the file pointer moves forward.In this section, you learned how to read files using readline(), readlines(), and a for loop. You also compared these methods, explored practical examples, and learned when each approach is most appropriate. In the next section, you will learn about file pointers, the tell() and seek() methods, reading binary files, efficiently processing large files, and performance optimization techniques.
In the previous section, you learned how to read files using read(), readline(), readlines(), and for loops. While these methods are sufficient for most situations, understanding the file pointer is essential when working with large files or when you need to read the same file multiple times. Python also provides methods to determine and change the current reading position within a file.
In this section, you will learn how file pointers work, explore the tell() and seek() methods, read binary files, process large files efficiently, and understand performance optimization techniques.
Whenever Python opens a file, it maintains an internal marker called the file pointer. This pointer keeps track of the current reading or writing position inside the file.
Initially, the file pointer is positioned at the beginning of the file.
Student.txt
Rahul
Python
92
Before reading any data, the pointer is located at the first character.
file = open("student.txt", "r")
print(file.read(5))
print(file.read(7))
file.close()
Output
Rahul
Python
The second read() continues from where the first one stopped because the file pointer automatically moves forward.
tell() MethodThe tell() method returns the current position of the file pointer.
file.tell()
file = open("student.txt", "r")
print(file.tell())
file.read(5)
print(file.tell())
file.close()
Output
0
5
Initially, the pointer is at position 0. After reading five characters, it moves to position 5.
seek() MethodThe seek() method moves the file pointer to a specified position.
file.seek(position)
file = open("student.txt", "r")
print(file.read(5))
file.seek(0)
print(file.read())
file.close()
Output
Rahul
Rahul
Python
92
After moving the pointer back to position 0, Python reads the file again from the beginning.
seek() with Different Positionsfile = open("student.txt", "r")
file.seek(6)
print(file.read())
file.close()
Output
Python
92
The pointer skips the first six characters before reading.
Large files should not be loaded entirely into memory. Instead, process them one line at a time.
file = open("large_data.txt", "r")
for line in file:
print(line.strip())
file.close()
This approach is memory-efficient because only one line is processed at a time.
For extremely large files, reading fixed-size chunks improves performance.
file = open("large_data.txt", "r")
while True:
chunk = file.read(100)
if not chunk:
break
print(chunk)
file.close()
The program reads 100 characters at a time until the end of the file.
Binary files such as images, videos, and PDF documents must be opened using binary mode.
file = open("photo.jpg", "rb")
data = file.read(20)
print(data)
file.close()
Output
b'\xff\xd8\xff\xe0...'
Binary files return byte objects instead of readable text.
for loop for very large text files.read().seek() instead of reopening the file repeatedly.| Application | How File Reading is Used |
|---|---|
| Log Analysis | Process log files line by line. |
| Data Analytics | Read large datasets efficiently. |
| Machine Learning | Load training data. |
| Image Processing | Read binary image files. |
| Backup Systems | Read large files in chunks. |
| Document Processing | Read reports and text documents. |
file = open("report.txt", "r")
print("Current Position:", file.tell())
print(file.read(10))
print("New Position:", file.tell())
file.seek(0)
print(file.read())
file.close()
Output
Current Position: 0
Python Fil
New Position: 10
Python File Handling Report
Consider the following program.
file = open("student.txt", "r")
print(file.tell())
file.read(5)
print(file.tell())
file.seek(0)
print(file.read())
file.close()
Execution Steps
0.5.seek(0) moves the pointer back to the beginning.Output
0
5
Rahul
Python
92
read() for extremely large files.seek() with an invalid position.In this section, you learned how file pointers work, explored the tell() and seek() methods, learned efficient techniques for reading large files, and understood how to read binary files. You also explored performance tips, practical examples, and common beginner mistakes. In the final section, you will review the complete lesson through a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Writing and Appending Files in Python.
In this lesson, you learned how to read files in Python using different built-in methods. Reading files is one of the most common operations in Python because applications frequently need to retrieve information stored in text files, configuration files, log files, datasets, and binary files.
You began by understanding why reading files is important and how to open files in read mode using the open() function. You also learned about file objects and how Python represents an opened file.
Next, you explored different file reading methods including read(), readline(), readlines(), and reading files using a for loop. You compared these methods and learned when each approach should be used.
Finally, you learned about the file pointer, the tell() and seek() methods, reading large files efficiently, reading binary files, performance optimization techniques, and best practices for file reading.
Understanding these concepts prepares you to process files efficiently in real-world Python applications, including data analysis, machine learning, web development, automation, and system administration.
open(filename, "r").read() reads the complete file or a specified number of characters.readline() reads one line at a time.readlines() returns all lines as a list.for loop is the most memory-efficient way to process large text files.tell() returns the current pointer position.seek() moves the pointer to a specified location.rb) for images, videos, PDFs, and other binary files.The r mode is used to read an existing file.
read() method do?It reads the entire file or a specified number of characters.
read() and readline()?read() reads multiple characters or the entire file, while readline() reads one line at a time.
readlines() return?It returns all lines of a file as a list.
for loop recommended for large files?Because it reads one line at a time, reducing memory usage.
It is an internal marker that tracks the current position inside a file.
tell() method return?It returns the current position of the file pointer.
seek() method?It moves the file pointer to a specified position.
The rb mode.
Reading the file line by line using a for loop or processing it in chunks.
read().readline().readlines() to store all lines in a list.for loop.strip() to remove newline characters while displaying file contents.tell().seek(0).rb mode.read() method?read(), readline(), and readlines().for loop more efficient?tell() method.seek() method.Create a Python program that demonstrates different file reading techniques.
Your program should:
read().readline().for loop.tell().seek(0).========== FILE READER APPLICATION ==========
Opening File...
Reading Complete File
Python File Handling
Reading Files
Writing Files
Reading First Line
Python File Handling
Current File Pointer
46
Pointer Reset Successfully
Reading Again
Python File Handling
Reading Files
Writing Files
File Closed Successfully
============================================
Congratulations! You have successfully learned how to read files in Python using different techniques. You now understand how to use read(), readline(), readlines(), file iteration, file pointers, and efficient strategies for processing both text and binary files.
In the next lesson, you will learn Writing and Appending Files in Python: Complete Guide for Beginners. You will explore the write() and writelines() methods, append new data using a mode, overwrite existing files, work with multiple lines, and apply best practices for safely writing data to files.