Python 3: Files and Exception Handling

๐ŸŽฏ Goal:

By the end of this lesson, youโ€™ll be able to:

  • Read and write files in Python
  • Handle errors using try-except
  • Work with real data like CSV and JSON

๐Ÿ“„ 1. Reading and Writing Text Files

๐Ÿ“ Writing to a File

with open("notes.txt", "w") as file:
    file.write("This is your first file write in Python!\n")
    file.write("Welcome to the file world.")

"w" creates a new file or overwrites an existing one.

๐Ÿ“– Reading a File

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

๐Ÿ” Line-by-Line Reading

with open("notes.txt", "r") as file:
    for line in file:
        print(line.strip())

โž• Appending to a File

with open("notes.txt", "a") as file:
    file.write("\nAnother line added.")

๐Ÿงพ 2. Handling CSV Files

import csv

with open("data.csv", mode="w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Role"])
    writer.writerow(["Prince", "Analyst"])

Reading CSV:

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

๐ŸŒ 3. JSON Basics (Web-Friendly Format)

import json

person = {"name": "Prince", "skills": ["Python", "SQL"]}
json_data = json.dumps(person)
print(json_data)  # convert to JSON string

# Save to file
with open("person.json", "w") as f:
    json.dump(person, f)

# Load from file
with open("person.json", "r") as f:
    loaded = json.load(f)
    print(loaded["name"])

โš ๏ธ 4. Exception Handling

Errors happen โ€” Python gives you a way to handle them gracefully.

Try-Except Block

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Oops! Can't divide by zero.")

Catching Multiple Exceptions

try:
    x = int("abc")
except (ValueError, TypeError) as e:
    print(f"Error occurred: {e}")

Finally Block

try:
    f = open("test.txt", "r")
except FileNotFoundError:
    print("File not found!")
finally:
    print("Cleanup complete.")

โœ… Practice Time

Try these in your blog_env:

  • Write a list of your favorite books to a file
  • Read from that file and print each book
  • Create a CSV file with name, age, city
  • Use try-except to catch file not found or zero division errors

๐Ÿ“˜ Summary

  • You learned how to read/write files, handle CSV/JSON
  • You handled exceptions cleanly with try-except
  • You now have the tools to build real-world data scripts

Comments

Leave a comment