File handling and exception handling are essential concepts in Python, enabling developers to work with files efficiently and manage runtime errors gracefully. In this blog, we will explore how to handle files in Python and manage exceptions using try-except blocks.
Table of Contents
Python File Handling
Python provides built-in functions to work with files. The open()
function is used to open files, while various modes allow us to read, write, and append data.
Opening a File
The open()
function accepts two parameters: filename and mode.
file = open("example.txt", "r") # Opens the file in read mode
File Modes
Mode | Description |
---|---|
"r" | Read mode (default). Opens a file for reading. |
"w" | Write mode. Creates a new file or truncates an existing file. |
"a" | Append mode. Adds content to the end of an existing file. |
"x" | Exclusive creation mode. Fails if the file already exists. |
"b" | Binary mode. Used for non-text files like images. |
"r+" | Read and write mode. Does not truncate the file. |
"w+" | Write and read mode. Truncates the file before writing. |
Reading from a File
Python provides multiple ways to read files:
with open("example.txt", "r") as file:
content = file.read() # Reads entire content
print(content)
Other reading methods:
file.readline() # Reads one line at a time
file.readlines() # Reads all lines into a list
Writing to a File
To write data to a file, use write (w
) or append (a
) mode:
with open("example.txt", "w") as file:
file.write("Hello, Python!")
Appending content:
with open("example.txt", "a") as file:
file.write("\nAppending new content.")
Writing to a CSV File
Python provides the csv
module to handle CSV files:
import csv
data = [["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "Los Angeles"]]
with open("data.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
Writing to a JSON File
Python’s json
module allows easy JSON handling:
import json
data = {"name": "Alice", "age": 25, "city": "New York"}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Why Use with open()
Instead of open()
?
Using with open()
is recommended because:
- Automatic Resource Management: It ensures that the file is automatically closed when the block is exited, even if an error occurs.
- Prevents Resource Leaks: Not closing files manually can lead to resource exhaustion and unexpected behavior.
- Cleaner Code: The
with
statement provides better readability and removes the need for explicitclose()
calls.
Example:
# Recommended approach
with open("example.txt", "r") as file:
content = file.read()
# Not recommended approach (requires manual close)
file = open("example.txt", "r")
content = file.read()
file.close()
Closing a File
Python automatically closes a file when using with open()
. However, when using open()
manually, always close it:
file = open("example.txt", "r")
print(file.read())
file.close() # Always close the file to free resources
Exception Handling in Python
Python handles runtime errors using try-except blocks to prevent crashes and manage errors efficiently.
Basic Exception Handling
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except Exception as e:
print(e)
Using else
and finally
This both can be used to add extra feature to the try and except
else
: Runs if no exception occurs.finally
: Runs regardless of an exception.
try:
with open("example.txt", "r") as file:
content = file.read()
except Exception as e:
print(e)
else:
print("File read successfully:", content)
finally:
print("Execution completed.")
Conclusion
Python’s file handling and exception handling mechanisms provide powerful tools for working with files safely and managing errors effectively. Always use with open()
to handle files and wrap critical operations in try-except
blocks to make your code robust and error-free.
Want to explore more? Try building a simple log file system that stores error messages in a file whenever an exception occurs. Happy coding!