Search code examples
pythonglobos.path

Create a variable path using glob.glob and os.path.join in python


I am using Python 3.6 and would like to know how to create a variable path to locate a file based on a year folder that changes. I have the following file path:

C:\Users\al123\Desktop\scripts_test\tutorials\2021\Conference\Notes\single notes\Conference notes content.txt

This code gives me the correct files with the word "notes" in the name:

for name in glob.glob(r'C:\Users\al123\Desktop\scripts_test\tutorials\2021\**\*notes*.txt',recursive=True):
    print(name)

However, there is a 2021 folder and a 2022 folder, and I want it to change dynamically based on today's date. I will have a variable b that gives me the year based on today's date. Assuming that the path before the year folder is the same, when I try to add the variable b for the year using os.path.join it gives me nothing:

a=r'C:\Users\al123\Desktop\scripts_test\tutorials'
b=(date.today()-timedelta(days=1)).strftime('%Y')
c=r'**\*notes*.txt'
for name in glob.glob(os.path.join(a,b,c)):
    print(name)

What do I need to change in order to make it work?


Solution

  • This is a slightly different approach, but you could turn this into a lambda expression:

    plain_path = r'C:\Users\al123\Desktop\scripts_test\tutorials\{year}\**\*notes*.txt'
    variable_path = lambda year: plain_path.format(year=year)
    
    print(variable_path(2001))
    # C:\Users\al123\Desktop\scripts_test\tutorials\2001\**\*notes*.txt
    
    print(variable_path(2002))
    # C:\Users\al123\Desktop\scripts_test\tutorials\2002\**\*notes*.txt