Last Updated : 23 Jul, 2025
File handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely and efficiently.
Why do we need File HandlingTo open a file, we can use open() function, which requires file-path and mode as arguments:
Syntax:
file = open('filename.txt', 'mode')
Basic Example: Opening a File PythonNote: If you don’t specify the mode, Python uses 'r' (read mode) by default.
f = open("geek.txt", "r")
print(f)
This code opens the file demo.txt in read mode. If the file exists, it connects successfully, otherwise, it throws an error.
Closing a FileIt's important to close the file after you're done using it. file.close() method closes the file and releases the system resources ensuring that changes are saved properly (in case of writing)
Python
file = open("geeks.txt", "r")
# Perform file operations
file.close()
Checking File Properties
Once the file is open, we can check some of its properties:
Python
f = open("geek.txt", "r")
print("Filename:", f.name)
print("Mode:", f.mode)
print("Is Closed?", f.closed)
f.close()
print("Is Closed?", f.closed)
Output:
Filename: demo.txt
Mode: r
Is Closed? False
Is Closed? True
Explanation:
Reading a file can be achieved by file.read() which reads the entire content of the file. After reading the file we can close the file using file.close() which closes the file after reading it, which is necessary to free up system resources.
Example: Reading a File in Read Mode (r)
Python
file = open("geeks.txt", "r")
content = file.read()
print(content)
file.close()
Output:
Using with StatementHello world
GeeksforGeeks
123 456
Instead of manually opening and closing the file, you can use the with statement, which automatically handles closing. This reduces the risk of file corruption and resource leakage.
Example: Let's assume we have a file named geeks.txt that contains text "Hello, World!".
Python
with open("geeks.txt", "r") as file:
content = file.read()
print(content)
Output:
Handling Exceptions When Closing a FileHello, World!
It's important to handle exceptions to ensure that files are closed properly, even if an error occurs during file operations.
Python
try:
file = open("geeks.txt", "r")
content = file.read()
print(content)
finally:
file.close()
Output:
Hello, World!
Explanation:
Related articles: Modes in File Handling
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4