Python & Files: Become a Digital Librarian 📚
Issue 18: Learn to Read and Write Files with Python!
Hello Pythoneers,
Ever wanted to be a digital librarian? 📖 With Python, you can be! We're about to learn how to read and write files, which are like special containers for storing information on your computer. Think of them as digital treasure chests full of secrets, stories, or even your favorite recipes! 🍪
Why Learn About Files?
Save Your Creations: Whether it's a high score in your game, a cool story you wrote, or a list of your favorite things, you can store it all in files to keep them safe and sound.
Read Others' Work: Want to explore a poem written by someone else or analyze data from a science experiment?Python lets you read files created by others, opening up a whole world of information!
Automate Boring Stuff: Tired of doing repetitive tasks like renaming a bunch of photos? Python can help you write code to do it automatically!
Open Sesame! The open()
Function
To use a file, you first need to open it with Python's open()
function. It's like using a key to unlock the treasure chest. This function needs two things:
File Name: The name of your file, just like "my_story.txt" or "high_scores.txt".
Mode: How you want to use the file:
"r"
for reading (like opening a book to read a story)"w"
for writing (like grabbing a pen and paper to write a new story)"a"
for appending (like adding a new chapter to an existing story)
Reading a File:
# Imagine we have a file called "story.txt"
with open("story.txt", "r") as file:
story = file.read() # Read the entire file
print(story)
# Or read line by line:
with open("story.txt", "r") as file:
for line in file:
print(line)
Writing to a File:
# Create a new file or overwrite an existing one
with open("shopping_list.txt", "w") as file:
file.write("Apples\nBananas\nMilk\n")
Let's Practice! Coding Challenges:
Greeting Card: Write a program that asks for a person's name and creates a file called "greeting.txt" with a personalized greeting inside.
High Score Tracker: Create a program that keeps track of the highest score in a game. Each time the game is played, it should read the current high score from a file, compare it to the new score, and update the file if the new score is higher.
Favorite Things: Write a program that lets the user add their favorite things to a list stored in a file.
[Answers in my next newsletter, Please subscribe!].
Poll Time! 🗳️
Stay Tuned!