python 如何在路径位置中使用f字符串

nhaq1z21  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(171)

我只想在f字符串中使用filename变量,这里我遗漏了什么?

# generating file name
filename = 'AG' + datetime.date.today().strftime("%m%d%Y")

# saving file
df.to_csv(f'C:\Users\username\Documents\folder1\folder2\{filename}.csv', index=False, sep=',')
    • 错误:**
df.to_csv(f'C:\Users\username\Documents\folder1\folder2\{filename}.csv', index=False, sep=',')
              ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
uz75evzq

uz75evzq1#

问题出在字符串中的反斜杠,而不是fstring格式。您需要使用\\来转义Windows样式路径中的反斜杠,因为单个反斜杠表示转义字符,例如\n表示换行符,\t表示制表符。
就像@dawg提到的,你也可以把fr原始字符串结合起来,这样python就不会转义任何字符。

bakd9h0s

bakd9h0s2#

正如tiega提到的,您遇到的问题是\构造f字符串的问题。
作为一种更可靠的方法,您可以考虑使用pathlib来操作路径。
示例:

import datetime 
from pathlib import Path, PureWindowsPath

filename = 'AG' + datetime.date.today().strftime("%m%d%Y")
fp=Path(r'C:/Users/username/Documents/folder1/folder2', filename+'.csv')
# you could actually use this unmodified to open the file on Windows...

print(PureWindowsPath(fp))
# show the Windows presentation of that path
# C:Users\username\Documents\folder1\folder2\AG05072020.csv

相关问题