Error Handling and File Operations in Python: Read, Write, and Handle Exceptions Like a Pro

As you write real-world Python programs, two things will become unavoidable:

  1. Reading and writing files (to store or fetch data)
  2. Errors and exceptions (things that break your code unexpectedly)

In this lesson, you’ll learn:

  • How to read, write, and append text files
  • The right way to open and close files
  • What exceptions are and how to handle them
  • Common errors beginners face and how to solve them
  • How to use the try, except, finally blocks properly

Let’s break it all down clearly and practically.


📁 File Handling in Python

Python makes it easy to work with files text files, log files, CSVs, and more.


🔑 Basic Syntax to Open a File

Python
file = open("notes.txt", "r")  # 'r' = read mode

Modes:

  • "r" – Read (default)
  • "w" – Write (overwrites existing)
  • "a" – Append (adds to end of file)
  • "x" – Create a new file (error if exists)

✅ Reading a File

Python
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()

file.read() reads the full file
Always close the file when done.


📚 Read Line by Line

Python
file = open("notes.txt", "r")
for line in file:
    print(line.strip())
file.close()

strip() removes newlines or spaces at the end.


✅ Writing to a File

Python
file = open("log.txt", "w")
file.write("This is a new log entry.\n")
file.write("Second line of the log.")
file.close()

"w" overwrites existing content.


📌 Appending to a File

Python
file = open("log.txt", "a")
file.write("\nThis is an appended line.")
file.close()

"a" keeps existing content, adds new content to the end.


🧼 Better Way: Using with

Python
with open("notes.txt", "r") as file:
    content = file.read()
    print(content)

No need to explicitly close the file it happens automatically.


🧠 Let’s Build a Simple Notes App

Python
note = input("Write a note: ")

with open("mynotes.txt", "a") as file:
    file.write(note + "\n")

print("Note saved!")

⚠️ What Are Exceptions?

An exception is an error that occurs during the execution of your program.

Without handling it, Python will stop and show an error message (traceback).


❌ Common Errors

ErrorReason
FileNotFoundErrorFile you’re trying to read doesn’t exist
ZeroDivisionErrorYou tried dividing by zero
ValueErrorBad type for conversion/input
IndexErrorAccessed a list index that doesn’t exist
TypeErrorWrong data type used in an operation

🛡 Handling Exceptions Using try-except

Python
try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("You can't divide by zero!")
except ValueError:
    print("That wasn’t a valid number.")

🧱 Using finally: Always Runs

Python
try:
    file = open("data.txt")
    print(file.read())
except FileNotFoundError:
    print("The file was not found.")
finally:
    print("This block always runs error or not.")

✅ Raise Your Own Errors (Advanced)

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

if age < 0:
    raise ValueError("Age can't be negative.")

🧪 Example: Login with Error Handling

Python
try:
    username = input("Username: ")
    password = input("Password: ")

    if password != "admin123":
        raise PermissionError("Access denied.")
    print(f"Welcome, {username}!")

except PermissionError as pe:
    print(pe)

⚠️ Best Practices

Do thisInstead of this
Use with open() for filesAvoid forgetting file.close()
Catch specific exceptionsDon’t use plain except:
Keep error messages helpful and clearAvoid hiding or ignoring errors
Always test file paths existDon’t assume file will be there

💌 Stay Updated with PyUniverse

Want Python and AI explained simply straight to your inbox?

Join hundreds of curious learners who get:

  • ✅ Practical Python tips & mini tutorials
  • ✅ New blog posts before anyone else
  • ✅ Downloadable cheat sheets & quick guides
  • ✅ Behind-the-scenes updates from PyUniverse

No spam. No noise. Just useful stuff that helps you grow one email at a time.

🛡️ I respect your privacy. You can unsubscribe anytime.

Leave a Comment