Skip to main content

Command Palette

Search for a command to run...

Write_Journal.py: My Very First Script

What I am learning from my first script

Updated
6 min read
Write_Journal.py: My Very First Script
O

I am a beginner documenting my journey from scratch to my goal of being a capable web\software developer, with coding skills I can use to create actual value and make a living out of. hello@obakengcodes.com

Good day coders,

On my very first article, which you can read at www.obakengcodes.com, I mentioned how I was driven to learning how to program by my deep frustration of not finding a notebook style app that was tailored to my specific desires.

Today we will take a more technical look at how my first script looked, and what I have learned from it so far. Lets dive into the beginning of my_journal_project:

  1. The Full write_journal.py Script:

This is what the final product of my AI generated script looked like after some hours of debugging and mostly slow manual typing errors:

import os
from datetime import datetime

def write_entry():
    #1. get the current script directory(where write_journal.py is located)
    script_dir = os.path.dirname(os.path.abspath(__file__))

    #2. define the journal folder path inside the project directory
    journal_folder = os.path.join(script_dir, "journal_txts")

    #3. Ensure the journal folder exists(create if missing)
    if not os.path.exists(journal_folder):
        os.makedirs(journal_folder) #makes the folder if its not found
        print(f"file path: {journal_folder}")


    #4 Get the current date and time
    right_now = datetime.now()

    #5. format for display in the log
    formatted_date = right_now.strftime("%Y-%m-%d_%H:%M:%S")

    #6. create a safe filename based on the date and time(for uniqueness)
    file_name = right_now.strftime("%Y-%m-%d_%H-%M-%S") + ".txt"

    #7. combine folder path with the new filename
    file_path = os.path.join(journal_folder, file_name)

    #8. Prompt the user for their journal entry
    journal_entry = input("Tell me about your day:\n >")

    #9. wrap the entry with a timestamp for context
    log_entry = (f"[{formatted_date}] {journal_entry}\n")

    #10. write the entry to a new file inside journal_txts
    with open(file_path, "w") as file: # "w" = create new file
        file.write(log_entry)

    #11. confirm success to the user
    print(f"Entry saved successfully as '{file_name}'")

if __name__ == "__main__":
    write_entry()
  1. What I Am Still Learning:

After getting the script to actually work, I moved on to typing the two remaining ones. After the week long process of typing and debugging the codes so they could finally work well together. I realized that I really didn’t know how any of the code worked well enough for me to actually code it on my own.

I at first attempted to write the whole def write_entry() function from memory without looking. but after botching the paths section, I just couldn’t get a single line of code out of my memory to write the rest of the script. That is when I got humbled further and had to settle on practicing only parts of this one basic script before I could move any farther.

The logical option seemed to be to start at the top and start working my way down, so as I went over the script, I decided that breaking it down into these three parts would work best for me according to what I understood the script to be doing at the various paths;

  1. Paths and directory creation

  2. datetime and file naming

  3. entry input and file creation

I am only just starting to get a good enough grasp of the first path to actually be able to reliably write it on my own and even make longer and compact(shorter versions) of that part of the code, and understand how they relate to each other.

Once the Ai I am working with noted the progress I was making in grasping os.path… it started mentioning pathlib, which it said makes path scripts cleaner and allows for more functionalities, but I made a conscious decision to keep focusing on os.path for now and only explore pathlib when i get a confident grip on os.path.

Now that we have established what I am learning and what is still to be learned, let’s take a more focused look on how I have been practicing the paths part of the write_entry() function.

  1. How The Learning Looks:

After breaking the code down to three parts, the paths part included everything the script was doing from note #1 to #3. I went back to both deepseek and chat gpt, I find that getting two different perspectives helps me understand better and asked for a breakdown of each line of code to actually understand what os.path was actually doing in each case because writing from a place of understanding beats writing from memory by a long shot.

This is what a break up of the paths section of the script ended up looking like:

def write_entry():
    # Paths
    # 1. os.path.abspath gets the "directions"/path to the current script; write_journal.py
    current_file_path = os.path.abspath(__file__)

    # 2. os.path.dirname gets the path of the folder where write_journal.py is saved
    scr_dir = os.path.dirname(current_file_path)

    # 3. os.path.join defines a new folder path "journal_txts" and joins it inside of scr_dir
    journal_folder = os.path.join(scr_dir, "journal_txts")
    # the folder is not yet created, this line points to where it is expected to be found

    # 4. os.path.exists checks the address given to see if the folder is there
    # 5. And if not, os.makedirs creates the folder at that address before moving on
    if not os.path.exists(journal_folder):
        os.makedirs(journal_folder)
        print("journal folder created successfully.")

How it looks without the notes:

def write_entry():
    import os

    # paths
    current_file_path = os.path.abspath(__file__)
    scr_dir = os.path.dirname(current_file_path)
    journal_folder = os.path.join(scr_dir, "journal_txts")

    if not os.path.exists(journal_folder):
        os.makedirs(journal_folder)
        print("journal folder created successfully")

Anybody with more experience in python than me(beginner) can tell this is the longer way of doing this simple task, but practicing this breakdown a couple of times helped me understand what each line of code was doing. And only when I was confidently reproducing this process multiple times on my own, that is when my mind started experimenting with shortcuts and picking up where I could squeeze more work into one line.

As you will see, compacting is not really about skipping any process. It is more nesting each task into the same line, so understanding each line first is vital.

After a few failed experiments and asking why some of my compacted lines weren’t working, I got to the point where I could do all of the above work in as few lines as possible.

like this;

def write_entry():
    import os

    # Paths
    jfpath = os.path.join(os.dirname(__file__), "journal_txts")
    os.makedirs(jfpaths, exist_ok=True)

jfpath = assigns the result of everything that happens on the right side to the the variable jfpath(journal folder path) on the left side.

os.path.join() joins os.path.dirname(__file__) the directory name where the script or (__file__) is saved, with the name of the folder we want to create inside of that directory “journal_txts” all on one line.

Then os.makedirs(jfpath, tells the computer to create the folder we want, but exist_ok=True) also tells it its okay/or to ignore the instruction if the file already exists. This is a neat little trick AI suggested after establishing that I fully understood if not os.path.exists():.

  1. Conclusion:

Today I can break this paths concept down and write variations of this code without even opening my code editor or one of the chat bots. This makes me really proud of myself and now I look forward to learning more concepts as my_journal_project progresses further and grows in complexity to include sql database file handling, rich text editing, UI, and more…

If you would like to see how I moved on to practicing and improving on the second part of the code; datetime and file naming, consider bookmarking my website as I plan to publish that part soon. It turns out that I actually enjoy writing these blogs and documenting my journey, and I will be writing and posting much more frequently than I thought, I hope you learned something from reading up to this point.

print(“May your coding journey be fulfilling and fruitful. Until next post ;)”)

My Journal Project

Part 2 of 2

In this series I focus on the actual work and progress I am making on my first project while learning python. I will cover concepts that I learn, post my code as it starts and evolves, and anything else related to the my_journal_project.

Start from the beginning

write_journal.py: Datetime, File naming and File creation.

I Learned The Rest Of The Script

More from this blog

F

From Stuck to Coding

3 posts

Documenting my journey from dead-end jobs to coding career. Follow my raw, unfiltered path learning Python while building real projects. No experience to developer.