π― 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-exceptto 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

Leave a Reply