[Zero To Python] Day 10 - Reading Journal Entries From File
Learning to read()
The last couple days of this course have been about writing journal entries to a file. Today we take the next step forward and read the file back into our program. This makes our program much more useful as we can go back and view journal entries we already wrote.
And lucky for us, Python makes this simple. So, let’s go!
Reading Files With Python
The first thing to do is to create a new file called
read.py. This is where we are going to write the code to read in our file.
read.py write the following code:
When you run
read.py you should get the following output:
NOTE: Your output should reflect the contents of
test.txt, so it could be quite a bit different than what is shown here.
Okay, let’s talk about the code. The code is nearly identical to what we used to write to a file.
There are two big differences. First, for reading we use the
r flag when opening a file. This ensures we only use the file to read, and not write. Second, we call
my_file, which reads in the contents of the file. We use the variable
journal_data to store the contents of the file and then print that out at the end of our program.
If you change
test.txt and re-run
read.py, you should see the file changes reflected in your program output.
So, that’s how you read in file data with Python. Simple. :-)
The assignment today is to create your own
read.py to be able to read in the contents of
test.txt and output that to the screen.
For bonus fun, you could see what happens if you try to write to file with the
r flag set. What kind of error do you get?
Building Step By Step
Today was about taking another useful step forward. I hope you are starting to see how programs are built step by step. Each feature can be added a little bit at a time. Before you know it, you have a useful piece of software.
You are now one third of the way through this course. Isn’t that wild?!
Okay… well… come back tomorrow for more!
P.S. Go here for the full course index → Zero To Python In 30 Days
NOTE: I found the hilarious dog with glasses photo for the thumbnail on Unsplash.