我只想在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
2条答案
按热度按时间uz75evzq1#
问题出在字符串中的反斜杠,而不是fstring格式。您需要使用
\\
来转义Windows样式路径中的反斜杠,因为单个反斜杠表示转义字符,例如\n
表示换行符,\t
表示制表符。就像@dawg提到的,你也可以把
f
和r
原始字符串结合起来,这样python就不会转义任何字符。bakd9h0s2#
正如tiega提到的,您遇到的问题是
\
构造f字符串的问题。作为一种更可靠的方法,您可以考虑使用pathlib来操作路径。
示例: