python 连接文本和变量以创建路径

sf6xfgos  于 2022-10-30  发布在  Python
关注(0)|答案(4)|浏览(102)

我有以下3个变量:

Year=2022
Month=09
Filename=asd

我需要创建以下路径:

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

如何创建包含反斜杠符号的路径?

lmvvr0a8

lmvvr0a81#

year=2022
month=9
filename='asd'

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

编辑:

  • 将月份的格式设置为08, 09, 10而不是8, 9, 10
  • 添加r以忽略转义字符(\
rxztt3cl

rxztt3cl2#

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

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

xxb16uws3#

在构造路径名时,应该始终考虑使用os.path.join
大概是这样的:

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)

请注意,这是如何消除对路径分隔符或原始字符串的需要的

rekjcdws

rekjcdws4#

使用f字符串

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

相关问题