Mastering File Handling in Python: A Complete Guide
File handling is an essential skill in Python, as it allows you to read, write, update, and delete files. In this blog, we’ll explore various file operations and modes, handling text and binary files, managing file pointers, handling exceptions, and even working with temporary files. Let's dive in!
File Modes Overview
Python’s open()
function lets you specify modes:
'r': Read-only mode
'w': Write mode (overwrites if file exists)
'a': Append mode
'b': Binary mode
't': Text mode (default)
'x': Create mode (fails if file exists)
Basic Operations
Opening and Reading a File
The open()
function opens a file, and the read()
function reads its content. It’s a best practice to close files after use.
file = open("example.txt", "r")
print(file.read())
file.close()
Output (example):
Hello, this is the content of example.txt.
Using with
to Open Files
Using with
automatically closes the file.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Writing to a File
Write Mode
This overwrites the file if it exists or creates a new one.
with open("example.txt", "w") as file:
file.write("Hello World")
Reading it back:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Output:
Hello World
Appending to a File
with open("output.txt", "a") as file:
file.write("Fourth Line\n")
Reading Specific Parts of a File
Reading a Certain Number of Characters
with open("output.txt", "r") as file:
content = file.read(10)
print(content)
Output:
First line
Using tell()
and seek()
tell()
returns the current pointer position.seek()
sets the pointer to a specific location.
with open("output.txt", "r") as file:
print(file.read(10)) # Reads first 10 characters
print(file.tell()) # Shows the position (10)
file.seek(0) # Resets pointer to beginning
print(file.read(10)) # Reads first 10 characters again
Output:
First line
10
First line
Binary File Handling
Binary files, like images, are read and written in binary mode.
with open("image.jpg", "rb") as source_file:
with open("copy.jpg", "wb") as dest_file:
dest_file.write(source_file.read())
Exception Handling
Handle exceptions to prevent crashes when files don't exist or can’t be accessed.
try:
with open("notexist.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file doesn't exist.")
Output:
The file doesn't exist.
Using the os
and shutil
Libraries
These libraries let you manage files, like deleting or moving them.
import os
import shutil
try:
os.remove("copy.jpg")
except FileNotFoundError:
print("The file is not present.")
# Moving a file
shutil.move("image.jpg", "Files/image.jpg")
Temporary Files
The tempfile
module allows creating temporary files that are deleted once closed.
import tempfile
with tempfile.TemporaryFile(mode="w+t") as temp_file:
temp_file.write("Temporary content\n")
temp_file.seek(0)
print(temp_file.read())
Output:
Temporary content
Conclusion
With Python's extensive file handling capabilities, you can efficiently manage data across different file formats and sizes. Whether working with text or binary files, handling errors, or creating temporary files, file handling is a powerful tool in Python’s toolkit.
Subscribe to my newsletter
Read articles from Krishnat Ramchandra Hogale directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Krishnat Ramchandra Hogale
Krishnat Ramchandra Hogale
Hi! I’m Krishnat, a Senior IT Associate specializing in Performance Engineering at NTT DATA SERVICES. With experience in cloud technologies, DevOps, and automation testing, I focus on optimizing CI/CD pipelines and enhancing infrastructure management. Currently, I'm expanding my expertise in DevOps and AWS Solutions Architecture, aiming to implement robust, scalable solutions that streamline deployment and operational workflows.