As you write real-world Python programs, two things will become unavoidable:
- Reading and writing files (to store or fetch data)
- 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
Error | Reason |
---|---|
FileNotFoundError | File you’re trying to read doesn’t exist |
ZeroDivisionError | You tried dividing by zero |
ValueError | Bad type for conversion/input |
IndexError | Accessed a list index that doesn’t exist |
TypeError | Wrong 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 this | Instead of this |
---|---|
Use with open() for files | Avoid forgetting file.close() |
Catch specific exceptions | Don’t use plain except: |
Keep error messages helpful and clear | Avoid hiding or ignoring errors |
Always test file paths exist | Don’t assume file will be there |