Reading files is a common task in Python. It allows programs to access data stored in files, such as text files, logs, configuration files, or datasets.
Python provides built-in functions to open and read files easily.
π Opening a File
To read a file, you must first open it using the open() function.
Syntax:
file = open("filename", "mode")
- filename β name of the file
- mode β how the file will be used
For reading files, the mode is "r".
Example:
file = open("data.txt", "r")
π Reading the Entire File
The read() method reads the entire content of a file.
Example:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
π Reading Line by Line
The readline() method reads one line at a time.
Example:
file = open("data.txt", "r")
line = file.readline()
print(line)file.close()
To read multiple lines:
file = open("data.txt", "r")
print(file.readline())
print(file.readline())file.close()
π Reading All Lines as a List
The readlines() method reads all lines and stores them in a list.
Example:
file = open("data.txt", "r")
lines = file.readlines()
print(lines)file.close()
Output example:
['Hello\n', 'Welcome to Python\n', 'File Handling\n']
π Reading Files Using a Loop
A common way to read files is using a for loop.
Example:
file = open("data.txt", "r")
for line in file:
print(line)file.close()
β
Using with open() (Recommended)
The with statement automatically closes the file after reading.
Example:
with open("data.txt", "r") as file:
content = file.read()
print(content)
Advantages:
β Automatically closes the file
β Cleaner and safer code
π Example File
Suppose data.txt contains:
Hello
Python Programming
File Handling Example
Python code:
with open("data.txt", "r") as file:
for line in file:
print(line)
Output:
Hello
Python Programming
File Handling Example
π§ File Reading Modes
| Mode | Description |
|---|---|
r | Read file (default) |
rb | Read binary file |
r+ | Read and write |
π§Ύ Summary
Python provides several ways to read files:
read()β reads entire filereadline()β reads one linereadlines()β reads all lines into a listwith open()β safest way to handle files