Home > database >  Concatenate text and variables to create a path
Concatenate text and variables to create a path

Time:10-29

I have the following 3 variables:

Year=2022
Month=09
Filename=asd

And I need to create the following path:

"C:\Documents\2022\09_September\asd.xlsx"

How can I create that path including the backslash symbols?

CodePudding user response:

year=2022
month=9
filename='asd'

path = fr"C:\Documents\{year}\{month.zfill(2)}_September\{filename}.xlsx"

Edit:

  • format the month in the format 08, 09, 10 instead of 8, 9, 10
  • add r to ignore escape characters (\)

CodePudding user response:

Year=2022
Month='09'
Filename='asd'

path = fr"C:\Documents\{Year}\{Month}_September\{Filename}.xlsx"

CodePudding user response:

Using f string

path = f"C:\Documents\{Year}\{Month}_September\{Filename}.xlsx"

CodePudding user response:

When constructing pathnames you should always consider using os.path.join

Something like this:

from os.path import join as JOIN

Year=2022
Month=9 # corrected
Filename='asd'

fullpath = JOIN('C:', 'Documents', str(Year), f'{Month:02d}_September', f'{Filename}.xlsx')

print(fullpath)

Note how this obviates the need for path separators or raw strings

  • Related