Handling Exceptions When Processing CSV and JSON Files in Python
This article explains how to use Python's try‑except and with statements to safely read and process CSV and JSON files, covering common errors such as missing files, permission issues, format problems, and providing best‑practice examples for robust error handling.
1. Python Exception Handling Basics
Python uses the try-except block to catch and handle exceptions. The basic syntax is as follows:
try:
# code that may raise an exception
except Exception as e:
# exception handling logic
print(f"Error occurred: {e}")
else:
# code executed if no exception occurs
print("Operation successful!")
finally:
# code that runs regardless of exception (e.g., close files)
print("Program execution finished.")2. Exception Capture in CSV File Processing
2.1 Exceptions When Reading Files
When reading a CSV file, you may encounter FileNotFoundError (file does not exist) or PermissionError (insufficient permissions), among other issues.
Example: Safely Read CSV File
import csv
try:
with open("data.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("Error: File not found!")
except PermissionError:
print("Error: No permission to access the file!")
except csv.Error as e:
print(f"CSV parsing error: {e}")
except Exception as e:
print(f"Unknown error: {e}")2.2 Data Format Exceptions
If the CSV format is irregular (e.g., inconsistent column count), you can catch csv.Error with a try-except block.
Example: Handle CSV Format Errors
try:
with open("malformed.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if len(row) != 3: # assume each row should have 3 columns
raise ValueError("CSV format error: inconsistent column count")
print(row)
except ValueError as e:
print(e)3. Exception Capture in JSON File Processing
3.1 JSON Parsing Errors
JSON files may raise json.JSONDecodeError when the format is incorrect (missing quotes, mismatched brackets).
Example: Safely Parse JSON File
import json
try:
with open("data.json", "r", encoding="utf-8") as file:
data = json.load(file)
print(data)
except FileNotFoundError:
print("Error: File not found!")
except json.JSONDecodeError as e:
print(f"JSON parsing error: {e}")
except Exception as e:
print(f"Unknown error: {e}")3.2 Data Type Errors
If the JSON data does not match the expected structure (e.g., missing fields), you can manually check and raise an exception.
Example: Validate JSON Data Structure
try:
with open("user.json", "r") as file:
user = json.load(file)
if "name" not in user or "age" not in user:
raise ValueError("JSON missing required fields")
print(f"Username: {user['name']}, Age: {user['age']}")
except ValueError as e:
print(e)4. Best Practice: Combine try-except with with Statements
with statement: automatically manages file resources, ensuring files are properly closed.
try-except : catches possible exceptions, preventing program crashes.
Example: Complete Safe CSV + JSON Processing
import csv
import json
def process_files():
try:
# Process CSV
with open("data.csv", "r") as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
print(row)
# Process JSON
with open("data.json", "r") as json_file:
data = json.load(json_file)
print(data)
except FileNotFoundError:
print("File not found!")
except (csv.Error, json.JSONDecodeError) as e:
print(f"Data parsing error: {e}")
except Exception as e:
print(f"Unknown error: {e}")
finally:
print("Data processing completed.")
process_files()5. Summary
Exception handling is essential in file processing to prevent crashes.
CSV files require handling FileNotFoundError , PermissionError , and csv.Error .
JSON files require handling JSONDecodeError and data structure errors.
Best practice: combine with and try-except to ensure resources are released and errors are handled gracefully.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.