Introduction
Every real-world application reads or writes data. Whether it’s user preferences, logs, or exported reports, file handling is unavoidable. But files can fail — missing files, permission errors, corrupted data. That’s where exception handling saves you.
In this post:
- Reading and writing TXT, JSON, CSV
try,except,else,finally- Best practices for robust code
Text Files: The Basics
Writing to a TXT file
python
with open("data.txt", "w") as file:
file.write("Hello, World!")
The with statement automatically closes the file. Never use open() without with in production code.
Reading from a TXT file
python
with open("data.txt", "r") as file:
content = file.read()
print(content)
Modes: "r" = read, "w" = write (overwrites), "a" = append.
JSON Files: Structured Data
JSON is the universal language of APIs and config files.
Writing JSON
python
import json
data = {"name": "Alice", "age": 30}
with open("user.json", "w") as file:
json.dump(data, file, indent=4)
Reading JSON
python
with open("user.json", "r") as file:
data = json.load(file)
print(data["name"]) # Alice
Always use indent for readability when writing JSON manually.
CSV Files: Tabular Data
CSV (Comma-Separated Values) is everywhere in data exports.
Reading CSV
python
import csv
with open("employees.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Writing CSV
python
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Bob", 25])
newline="" prevents blank lines between rows on Windows.
Exception Handling: Preventing Crashes
Files don’t always exist. Networks fail. JSON gets corrupted.
Basic try-except
python
try:
with open("missing.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found. Creating a new one.")
with open("missing.txt", "w") as file:
file.write("Default content")
Multiple Exceptions
python
try:
value = int(input("Enter number: "))
result = 10 / value
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
else and finally
else: Runs if no exception occurred.finally: Always runs (cleanup code).
python
try:
file = open("log.txt", "r")
except FileNotFoundError:
print("File missing")
else:
print("File read successfully")
finally:
print("Execution complete")
Best Practices
- Catch specific exceptions — never use bare
except:. - Use
withfor files — automatic closing. - Log exceptions in production apps instead of just printing.
- Validate JSON before parsing.
Summary
| File Type | Read Method | Write Method |
|---|---|---|
| TXT | open().read() | open().write() |
| JSON | json.load() | json.dump() |
| CSV | csv.reader() | csv.writer() |
Leave a Reply