Hello Pythoneers,
Welcome back to our file manipulation detective agency! 🔍 Last time, we mastered the basics of reading and writing text files. Now, let's dive deeper into the world of files and become expert data detectives!
File Types: Unmasking the Clues
Just like clues in a mystery, files come in different formats. Python can work with a variety of them:
Plain Text Files (.txt): These are the simplest kind, containing just plain text, like a story you write in a notebook. 📝
CSV Files (Comma-Separated Values) (.csv): These are like spreadsheets that store data in rows and columns, separated by commas. Imagine a table with your friends' names, ages, and favorite ice cream flavors! 🍦
JSON Files (JavaScript Object Notation) (.json): This format is a bit like a Python dictionary. It's a way to store data in an organized way, often used to share information between different programs. Think of it as a secret code that computers can understand. 🔐
Reading a CSV File:
import csv
with open("classmates.csv", "r") as file:
reader = csv.reader(file)
# Skip the header row if there is one
next(reader)
for row in reader:
name, age, favorite_ice_cream = row
print(f"{name}, age {age}, loves {favorite_ice_cream} ice cream!")
Reading a JSON File:
import json
with open("game_data.json", "r") as file:
data = json.load(file)
print("High score:", data["high_score"])
print("Last played:", data["last_played"])
Handling File Errors: Don't Panic!
Sometimes, things can go wrong when working with files. Maybe the file doesn't exist, or you don't have permission to open it. Python has a built-in safety net called try-except
to catch these errors and prevent your code from crashing.
try:
with open("top_secret_file.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("Oops! That file is missing! Maybe it's hidden somewhere...")
except PermissionError:
print("Sorry, you don't have permission to read this file. It's top secret!")
except Exception as e: # Catching any other unexpected errors
print("Uh oh, something went wrong:", e)
Let's Solve Some Mysteries! Coding Challenges:
CSV Detective: Write a program that reads a CSV file containing information about different animals and their habitats. Let the user enter an animal's name and display its habitat.
JSON Decoder: Create a program that reads a JSON file with information about your favorite superheroes (e.g., name, powers, secret identity). Display their information in a fun and creative way!
Error-Proofing Expert: Write a program that repeatedly asks the user for a filename until they enter one that exists and can be opened in read mode. Once the file is successfully opened, print the first 5 lines of the file.
[Answers on the next newsletter, Please Support & Subscribe]
Poll Time! 🗳️
Happy Coding!
Answers to Issue 18: File handling part 1 challenges
Challenge 1: Greeting Card
def create_greeting_card():
name = input("Enter the person's name: ")
message = f"Dear {name},\n\nHappy coding with Python!\n\nSincerely,\nThe Young Pythoneers"
with open("greeting.txt", "w") as file:
file.write(message)
print("Greeting card created in greeting.txt")
create_greeting_card()
Challenge 2: High Score Tracker
def update_high_score(new_score):
try:
with open("high_score.txt", "r") as file:
high_score = int(file.read())
except FileNotFoundError:
high_score = 0 # If file doesn't exist, start with 0
if new_score > high_score:
with open("high_score.txt", "w") as file:
file.write(str(new_score))
print("Congratulations! New high score:", new_score)
# Example usage (replace with actual new score)
update_high_score(1500)
Challenge 3: Favorite Things
def add_favorite_thing():
thing = input("Enter your favorite thing: ")
with open("favorites.txt", "a") as file:
file.write(thing + "\n")
print(f"{thing} added to your favorites!")
def view_favorites():
try:
with open("favorites.txt", "r") as file:
favorites = file.readlines()
if favorites:
print("Your favorite things:")
for item in favorites:
print(item.strip()) # Remove newlines
else:
print("Your favorites list is empty.")
except FileNotFoundError:
print("You don't have a favorites list yet.")
# Example usage
while True:
action = input("Add (a) or view (v) favorites? (q to quit): ")
if action == 'a':
add_favorite_thing()
elif action == 'v':
view_favorites()
elif action == 'q':
break
else:
print("Invalid choice.")