Search code examples
pythonpython-3.xpython-os

Create a directory today and change to the new directory


My python code starts in a specific directory. From this directory, I would like my script to automatically create a new directory by today's date and then change to that directory.

import datetime
todays_date = datetime.datetime.today().strftime('%d_%B_%Y')
os.chdir(r'/Users/me/Desktop/project/')
if not os.path.exists(todays_date):
    os.makedirs(todays_date)

The code above works well. Now, I just need to change to that directory without manually typing today's date. How can I achieve that task?

os.chdir(f'/Users/me/Desktop/project/._todays_date)

returns SyntaxError: EOL while scanning string literal


Solution

    1. You didn't close the string correctly. You forgot the ending '
    2. You did not use f-strings correctly. To use a variable in a f-string, surround it with curly braces.
    os.chdir(f'/Users/me/Desktop/project/{todays_date}')
    

    should work.