write_journal.py: Datetime, File naming and File creation.
I Learned The Rest Of The Script

Good day coders,
If you missed the first article which covers how I managed to get my first script completed and working, including how I broke down the script to learn it in parts, You can check it out by clicking here.
Today we will be moving onto the second and third parts to reveal how the complete script looks, and the concepts I have managed to grasp. Because I am excited with the fact that i can write the whole script without checking previous versions, I will start by showing the full version of the script as I now prefer to write it, and then we will move on to the breakdown.
I initially planned to write an article for each part, but since I spent the last couple of days practicing, and I managed to comprehend the script much faster than I thought, I figured I might as well write about both parts so I can move on to practicing the second script: read_journal.py.
If anybody is following the series, please feel free to leave a comment and let me know if I should have wrote an article for each path, or if this combination was okay. I will surely take your feedback into consideration for future articles. I also want to welcome my first 🎉🙏🏽, I hope you find value as we walk this journey together.
Now, let’s take a look at how my script looks.
Full write_journal.py Script:
import os
from datetime import datetime
def write_entry():
# Paths
jfpath = os.path.join(os.path.dirname(__file__), "journal_files")
os.makedirs(jfpath, exist_ok=True)
# Datetime and File naming
fmt_date = datetime.now().strftime("Date: %Y-%m-%d Time: %H:%M:%S")
f_name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".txt"
f_path = os.path.join(jfpath, f_name)
# entry and file creation
entry = input("How was your day?:")
with open(f_path, "w") as file:
file.write(f"{[fmt_date]} {entry}")
print(f"file saved at: {f_path}")
# call function
if __name__ == "__main__":
write_entry()
Excited as I am that I understand the functions in this script enough to consistently write it without help, I must admit that I am not writing it clean without bugs, i.e missing a letter here or a comma there.
It bothered me at first, but apparently, even the decades long experienced coders still go through that experience. So it doesn’t bother me anymore, especially considering that I am able to understand the errors and correct them on my own.
We will cover some of the bugs as I go along the breakdown of this script. on the last article we already covered the paths section of the script.
Now we will get into the datetime and file naming part, as I reveal what I have learned below.
Datetime and File naming:
Datetime.now() is the function that captures the local current date and time at the exact moment when the function is called in the code. i.e it captures the year, month, day & Hour, minute, second.
strftime() is a method that specifies how a captured datetime should be represented as a string. In full the method’s name is “string format time”, which makes it self explaining for me to understand, so I think of it as taking the raw datetime and formatting it to be shown the way I want it to.
Together, I learned to use these to record a formatted time that will appear next to my entries, and another format of datetime which I use to name each new file with the date and time that the file was created.
After some experimenting on my own, I even managed to figure out how to make even more variations of how the date and time appears in my entries. Which is why I now added the words “Date:” and “Time:” to my {fmt_date} variable.
# Date time and File naming
# First i assign a formatted datetime to a variable called fmt_date for use inside my journal entries
fmt_date = datetime.now().strftime("Date: %Y-%m-%d Time: %H:%M:%S")
# Then i have to use the same function and method to create a file name
f_name = datetime.now().strftime("%Y=%m=%d_%H-%M-%S") + ".txt"
# I use os.path.join to define the file path inside f_path using the file name
f_path = os.path.join(jfpath, f_name)
We have to create two separate formats because inside a file you are free to use any characters as you write, but naming any file or folder is a different story.
Operating systems do not like file names with characters like colons (:) in them. I think it is because most of these characters are reserved for the os to use for instructions and other operations.
We also do it separately because we have to add the “.txt” at the end of the file name to let the computer know that it is a text file the next time we want to access it. One of my most reoccurring bugs is that I often forget to add the file extension at the end.
Another bug I often come across here is, at the top of my script when I am importing. I will often only write import datetime instead of from datetime import datetime, or I might misspell datetime when I write it the second time.
we covered os.path in the previous article so I wont go into it now.
That was the datetime and file naming section, let’s dive into the last section of the script below.
Entry and File Creation:
This was the hardest part for me to fully understand, which is where I also make most of my mistakes, but I am satisfied with the fact that even if I make a mistake and get an error while running the code, I easily know what the mistake is and I can easily correct it.
input() is a function that will prompt the user for input from a device’s keyboard, which we then assign to a variable called “entry”. The function allows for a prompt to be written inside of the inputbrackets, similar to the print function, incase a developer may want to guide a user on what kind of input to insert i.e; “How was your day?”.
open() is a function that simply takes a file path and opens that file. We can further let the program know what will be doing with the file by using the argument “w” for writing into a file, there are other arguments such as “r” for read, “a” for append, and more I think. (I often do not remember if I should add a comma after the file path or not.)
with is a statement that is used together with the open() function, it ensures the file is properly opened, but most importantly that it is automatically closed as soon as the program moves out of the indent area.
I learned that this makes the file handling smoother, and this is how almost all of files will be opened and closed by coders to avoid file corruptions and errors.
write() in write.file is a method that takes string inputs and returns them into the file that was opened. This method behaves according to what argument was used while opening the file. (Here I often get confused as to whether file or write comes first, I always end up writing it the other way and correcting it after running the script.)
Another thing I do is, I will often use the journal folders path instead of the file path in this section.
But when I get confused I just do it the way I think is right and run the script instead of checking the completed script, I feel prouder of myself when I fix the code this way.
Here is the code with some notes.
# Entry and File creation
# I use input to take a simple text based entry with no special formatting since this only runs in my terminal
entry = input("How was your day? ")
# Using (with open) we open the file path as a file to write "w" into it
with open(f_path, "w") as file:
# Then we write the formatted date and entry into it
file.write(F"{[fmt_date]} {entry}")
# then we print to let ourselves know the script ran sucessfully
print(f"file saved successfully as: {F_path}")
Conclusion:
I am now confident enough with all that I have learned above to move onto the next script; “read_journal.py”. I have also been experimenting more with the format, I am able to add new lines to make the entry look cleaner, I will cover this in the future.
With only this basic script, I have learned that once you push past the frustration it actually gets very exciting and dopamine-y when you start to get clarity and understanding.
I am afraid that if it continues like this I might start coding for the rush rather than anything. Haha I am joking… Probably ;-).
If you found anything of value in this article, please consider following the blog and commenting, I would like to know what you think of my journey or any advices that you may have.
I will soon start working on the second script and an article for it as soon as I feel like I have learned it thoroughly.
Until then🫡.



