File Handling & Exception Handling – Building Robust Python Applications


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
  • tryexceptelsefinally
  • 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

  1. Catch specific exceptions — never use bare except:.
  2. Use with for files — automatic closing.
  3. Log exceptions in production apps instead of just printing.
  4. Validate JSON before parsing.

Summary

File TypeRead MethodWrite Method
TXTopen().read()open().write()
JSONjson.load()json.dump()
CSVcsv.reader()csv.writer()


Jay Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *