[Zero To Python] Day 9 - Appending Journal Entries To File
Let’s fix the bug we just created...
It’s day nine of Zero To Python and today we are going to fix a bit of a bug we created yesterday. The code we wrote yesterday wrote a journal entry to a file. That’s great, but there is a problem. The file is overwritten every time we run our program.
That means we only save one day’s journal entry at a time. Not as useful as it should be. We need to fix the program to add new entries to the end of the file. So, let’s do that.
Python File Flags - Append vs Overwrite
To fix this problem you need to understand a bit about Python’s file flags. In the code we wrote yesterday it had an open()
method call with the mode flag w
set. In that mode, Python will remove the contents of the file and replace it with whatever we write to the file. In short, it overwrites the file every time.
What we want is append, not overwrite. That means changing our code to use the a
flag instead of w
. The code change looks like this:
If you run input.py
again, you get the same result as before on the output screen, but when you run it more than once you will get multiple journal entries saved to test.txt
.
That is the entire fix. Super easy!
Assignment
Fix the file writing code to use append mode instead of overwrite.
Useful Links
A Big Lesson
This might feel like a small change, but it’s meant to teach you a big lesson about programming.
The art of programming is often more about understanding the problem and solving it in a simple way than it is about writing a lot of code. That is why it’s important to read the documentation and learn the tools as you go. Using the right tool at the right time can save you hours of fruitless effort.
That’s all for today, see you tomorrow!
-Brian
FYI, there was a glitch in Substack and the image got screwed up when sending this out as an email. The website version of this newsletter issue is updated and fixed.