File Handling
Last Updated : 5th September 2025
File handling in Python is a fundamental concept that allows you to manipulate and work with files. It provides a way to create, read, write, and manipulate files on the local system.
📂 File Handling
In Python, you can work with files using the built-in open() function.
The open() function takes two arguments: the file name and the mode in which you want to open the file.
The mode can be one of the following:
- "r" (read mode): Opens the file for reading.
- "w" (write mode): Opens the file for writing. If the file does not exist, it will be created.
- "a" (append mode): Opens the file for appending. If the file does not exist, it will be created.
- "r+" (read/write mode): Opens the file for both reading and writing.
- "w+" (read/write mode): Opens the file for both reading and writing. If the file does not exist, it will be created.
- "a+" (read/write mode): Opens the file for both reading and writing. If the file does not exist, it will be created.
Note:- After you open a file, you can perform various operations on it, such as reading, writing, and closing it.
file = open("example.txt", "r")
content = file.read()
file.close()
Don't worry ! We will cover file handling in upcoming sections
With Statement
with statement is used to open a file and automatically close it after the block is executed.You don't need to call the close() method for closing the file.
with open("example.txt", "r") as file:
content = file.read()