Aragorn64
Aragorn64

Reputation: 129

Concatenate text and variables to create a path

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?

Upvotes: 0

Views: 178

Answers (4)

Adon Bilivit
Adon Bilivit

Reputation: 26993

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

Upvotes: 1

KillerRebooted
KillerRebooted

Reputation: 659

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

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

Upvotes: 2

Zack Walton
Zack Walton

Reputation: 196

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 (\)

Upvotes: 2

bedkan
bedkan

Reputation: 39

Using f string

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

Upvotes: 0

Related Questions