Python Files and Exception Basics

October 7, 2025

Working with files and handling exceptions are two essential parts of programming in Python.
Files let you store and retrieve data, while exceptions help your program deal with unexpected situations — like missing files, invalid inputs, or division by zero — without crashing.

In this blog, we’ll cover:

  • File Handling in Python (Open, Read, Write, Close)
  • File Modes
  • Using with Statement
  • Exception Handling (try, except, else, finally)
  • Common Exception Types
  • Raising Exceptions

📁 1. Python File Handling Basics

File handling allows you to read and write data to files stored on your computer.

Opening a File

You use the built-in open() function to work with files.

# Syntax:
file_object = open(filename, mode)

Common File Modes

ModeDescription
'r'Read mode (default). Opens file for reading.
'w'Write mode. Overwrites file if it exists or creates new one.
'a'Append mode. Adds data to the end of file.
'r+'Read and write mode.
'x'Create mode. Creates a new file; gives error if file exists.

Example 1: Reading a File

Suppose you have a file example.txt containing:

Hello, Python learners!
Welcome to file handling.

Here’s how to read it:

# Open the file in read mode
file = open("example.txt", "r")

# Read the content
content = file.read()
print(content)

# Always close the file after use
file.close()

Output:

Hello, Python learners!
Welcome to file handling.


Example 2: Reading Line by Line

file = open("example.txt", "r")

for line in file:
    print(line.strip())

file.close()

The strip() function removes newline characters at the end of each line.


Example 3: Writing to a File

file = open("notes.txt", "w")
file.write("Python file handling is easy!\n")
file.write("We are writing data to a file.")
file.close()

This will create or overwrite notes.txt with the given text.


Example 4: Appending to a File

file = open("notes.txt", "a")
file.write("\nAppending new content to the file.")
file.close()


Using the with Statement

Python provides a cleaner way to handle files using with.
It automatically closes the file, even if an error occurs.

with open("example.txt", "r") as file:
    data = file.read()
    print(data)

No need to call file.close() manually!


⚠️ 2. Python Exception Handling

An exception is an error that occurs during program execution.
Without handling it, your program can crash.

Example:

num1 = 10
num2 = 0
print(num1 / num2)  # ZeroDivisionError

This will stop your program with:

ZeroDivisionError: division by zero


Handling Exceptions with try...except

To handle such cases gracefully:

try:
    num1 = 10
    num2 = 0
    print(num1 / num2)
except ZeroDivisionError:
    print("You cannot divide by zero!")

Output:

You cannot divide by zero!


Using Multiple Except Blocks

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")


The else and finally Blocks

  • else: Executes if no exception occurs.
  • finally: Always executes (cleanup code, closing files, etc.)
try:
    file = open("example.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found!")
else:
    print("File read successfully!")
finally:
    print("File operation completed.")


🧱 3. Common Python Exceptions

ExceptionDescription
ZeroDivisionErrorDividing by zero
ValueErrorInvalid data type or conversion
TypeErrorWrong data type used in operation
FileNotFoundErrorFile doesn’t exist
IndexErrorAccessing out-of-range index
KeyErrorAccessing missing key in dictionary

🚨 4. Raising Exceptions Manually

You can raise exceptions using the raise keyword.

age = int(input("Enter your age: "))

if age < 18:
    raise ValueError("Age must be 18 or above.")
else:
    print("Access granted!")

If age < 18, it stops execution and shows:

ValueError: Age must be 18 or above.


🧩 Summary

ConceptDescription
open()Opens a file in specific mode
read(), write(), readlines()Read/write operations
with open()Automatically closes file
try...exceptHandle exceptions gracefully
else and finallyAdd extra control flow
raiseManually throw custom exceptions

💡 Example: File + Exception Together

try:
    with open("student_data.txt", "r") as file:
        for line in file:
            print(line.strip())
except FileNotFoundError:
    print("The file 'student_data.txt' was not found.")
finally:
    print("Program finished.")


✅ Key Takeaways

  • Always close your files (or use with open()).
  • Handle runtime errors using try-except.
  • Use finally for cleanup actions.
  • Combine file handling with exception handling for robust programs.

© Copyright 2025 Fessorpro

Terms of Service / Privacy Policy