Python File Handling
In Python, file handling is a way which allows us to create, read, write, and delete files. It is very useful when you want to store data permanently to view this data in future for different purposes, such as saving user information, error logs, reports, etc.
Why is File Handling Important?
The data disappears when the program ends without file handling, . With creating files, we can store and retrieve data even after the program stops.
Opening a File in Python
Python uses the built-in open()
function to open a file.
Syntax:
file = open("filename", "mode")
Mode | Description |
---|---|
'r' |
Read (default) |
'w' |
Write (creates new or overwrites file) |
'a' |
Append (adds data to end of file) |
'x' |
Create (fails if file exists) |
'b' |
Binary mode (e.g., 'rb' , 'wb' ) |
Example 1: Writing some data to a File
file = open("example.txt", "w") # Open in write mode
file.write("Hello, this is a write operation test.\n")
file.write("we are Writing to a file in Python.\n")
file.close() # Always close the file!
📝 The above code creates a file named example.txt
and writes two lines to it.
Example 2: Reading from a File
file = open("example.txt", "r") # Open in read mode
content = file.read()
print(content)
file.close()
📝 This reads and prints the contents of example.txt
.
Hello, this is a write test.
we are Writing to a file in Python.
Example 3: Appending (adding) to a File
file = open("example.txt", "a") # Open in append mode
file.write("Adding a new line.\n")
file.close()
📝 This will add a new line at the end of the file without deleting the old content.
Reading content Line by Line
file = open("example.txt", "r")
for line in file:
print(line.strip()) # Here, strip() removes newline characters
file.close()
Using with
Statement (Recommended)
Python provides a cleaner way to handle files using the with
statement. This automatically closes the file.
Example:
with open("example.txt", "r") as file:
data = file.read()
print(data)
By Using this way, you don not need to call file.close()
.
Deleting a File
You can delete a file using the os
module.
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted.")
else:
print("File does not exist.")
🔚 Summary
-
Use
open()
to work with files. -
Modes:
'r'
(read),'w'
(write),'a'
(append),'x'
(create). -
Always close the file after use (or use
with
). -
Use the
os
module for file operations like deleting or checking existence.
✅ Quick Tip:
Use with open(...) as f:
whenever possible. it is safe and cleaner.
By reading this tutorial you will be able to create files, append data to files, view the content of a file by opening the file, deleting a file and even closing a file just after use.