File handling in Python allows programs to store data permanently in files and retrieve data later.
Without file handling:
- Data is lost when the program stops
- Programs cannot save logs, reports, or user data
Why File Handling is Important ?
- store user data
- read configuration files
- write logs
- process large data
- work with reports and text files
Types of Files in Python :
Python mainly works with two types of files:
Text Files → .txt , .csv , .log
Binary Files → .jpg , .pdf , .exe , .dat
Opening a File :
The key function for working with files in Python is the open( ) function.
The open() function takes two parameters; filename, and mode.
Syntax :
Python
file_object = open("filename", "mode")
Modes :
| Mode | Description |
|---|---|
r | Read - Default value. Opens a file for reading, error if the file does not exist |
w | Write - Opens a file for writing, creates the file if it does not exist |
a | Append - Opens a file for appending, creates the file if it does not exist |
x | Create - Creates the specified file, returns an error if the file exists |
b | Binary mode |
t | Text mode |
Using With Statement :
The with statement automatically closes the file, even if an error occurs.
Python
with open("data.txt", "r") as file: print(file.read())