Chapter 12: Storing Your Data - Working with Files
So far, every program you've written has had a temporary memory. When the program finishes, all the data stored in your variables disappears. But what if you wanted to save information, like a high score from a game, a list of tasks, or notes you've taken?
To do this, you need to work with files. Reading from and writing to files allows your program to store data permanently on your computer's hard drive, so it can be used later.
Think of it this way: variables are like your short-term memory, while files are like a notebook you can write in and read from anytime.
The Three Key Operations
When working with files, there are three main things you'll want to do:
Reading (
'r'): Open a file to look at its contents.Writing (
'w'): Open a file and erase everything in it to write new content.Appending (
'a'): Open a file and add new content to the very end, without erasing what's already there.
The Best Way to Open a File: with open()
with open()To work with a file, you first have to open it. The best and safest way to do this in Python is with a with statement. This syntax is great because it automatically closes the file for you when you're done, even if errors occur.
Here's the basic structure:
with open('filename.txt', 'mode') as file_variable:
# Do something with the file here
# The file is automatically closed after this block
filename.txt: The name of the file you want to open. If it's not in the same directory as your Python script, you'll need to provide the full path to the file.mode: A single letter specifying what you want to do ('r','w', or'a').file_variable: A variable that will represent the opened file inside thewithblock.
Reading from a File
Let's start by reading. Imagine we have a file named hello.txt with the following content:
To read and print its contents, we use the 'r' mode.
Another common way to read a file is line by line, which is useful for very large files. You can do this by looping directly over the file variable:
The .strip() method is useful here because each line read from a file usually has an invisible newline character (\n) at the end. .strip() cleans that up for neater printing.
Writing and Appending to a File
Writing ('w')
'w')To write content to a file, use the 'w' mode.
Important Warning: If the file already exists, 'w' mode will completely erase all its contents before writing the new information. If the file doesn't exist, Python will create it for you.
After running this code, a new file greetings.txt will be created with two lines of text. Notice we have to add our own newline character (\n) if we want to start a new line.
Appending ('a')
'a')If you want to add to a file without erasing its contents, use the 'a' mode.
If you open greetings.txt now, you'll see:
A Mini-Project: A Simple Guest Book
Let's use this to create a simple guest book program. It will ask for the user's name and append it to a file.
Run this program, enter a few names, and then type quit. It will then show you all the names it saved to guest_book.txt.
Summary and What's Next
You've learned one of the most practical skills in programming: making data persistent.
You can read (
'r'), write ('w'), and append ('a') to files.The
with open(...)syntax is the best and safest way to handle files.Writing (
'w') overwrites, while appending ('a') adds to the end.
In our mini-project, you might have noticed the try...except block. What happens if we try to read a file that doesn't exist? Our program crashes! In the next chapter, we'll dive deeper into handling these kinds of situations gracefully by learning about errors and exception handling.
Practice Time!
Create a program that asks for your three favorite hobbies and writes each one to a new line in a file called
hobbies.txt.Write a second program that reads the
hobbies.txtfile and prints each hobby on a separate line.
Last updated