Brian Knapp’s Newsletter

Share this post

[Zero To Python] Day 9 - Appending Journal Entries To File

brianknapp.substack.com

[Zero To Python] Day 9 - Appending Journal Entries To File

Let’s fix the bug we just created...

Brian Knapp
Mar 19
1
1
Share this post

[Zero To Python] Day 9 - Appending Journal Entries To File

brianknapp.substack.com

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

  • Python file open() docs

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

P.S. Go here for the full course index → Zero To Python In 30 Days

1
Share this post

[Zero To Python] Day 9 - Appending Journal Entries To File

brianknapp.substack.com
1 Comment
author
Brian Knapp
Mar 19Author

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.

Expand full comment
Reply
TopNewCommunity

No posts

Ready for more?

© 2023 Brian Knapp
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing