Discover more from Brian Knapp’s Newsletter
[Zero To Python] Day 8 - Saving To Text Files
The files are in the computer?!
Now that we’ve played with strings quite a bit, it’s time to save journal entries to a text file. This will allow a journal entry to persist across multiple user sessions. In short, this makes our daily journal program useful!
So let’s get started.
Writing To A File In Python
The first thing we are going to do is create a new python file called
file.py. This is where we will write a bit of code to get a handle on opening up a file and writing some text. Inside
file.py write the following code:
Before we run the code, let me walk through it real quick. We start with creating a variable
fake_text and assign it a text string. The code prints out the string to give us an idea of what the value of
Next we get to the new bit. The code creates a variable called
my_file and sets its value to whatever the
open() function returns (which is a file object). We pass in the name of the file we are opening
test.txt and the mode flag
w. The next line writes the value of the
fake_text variable to the file. The last line calls
close() on our file which closes the file.
When you run
file.py you get the following output:
And if you look inside
test.txt it will have
abc123 and a newline saved there.
That is the basics of writing to a file in Python.
Writing Journal Entries To File
Now let’s go back to
input.py and add some new code to the end of the file. After your final
What this code does is takes the user input of
journal_text and writes it to a file instead of just printing it out to the screen. The code is very similar to the
my_file.write() instead of
print(). Also, newline characters are added to make the output in the file match our screen output.
If you run
input.py you get the following output:
And the journal entry should be written to the
Pretty cool, right?
The assignment today is to update the
input.py file to include code to write journal entries to a file. This isn’t overly complex code, but it is something that is worth understanding going forward.
For bonus, you could mess around with text formatting and other things when writing to file.
Moving From Prototype To Reality
As you can probably tell, we are quickly moving from a simple prototype into a useful program. In the next few days we will be adding even more useful features to this project. Before you know it, you’ll have a fully working version of the designs we started with.
So, keep having fun with this and I’ll see you in the next lesson!