Python 如何在路径位置中使用f字符串
我只想在我的文件中使用Python 如何在路径位置中使用f字符串,python,python-3.x,f-string,Python,Python 3.x,F String,我只想在我的文件中使用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:\User
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
问题在于字符串中的反斜杠,而不是fstring格式。您需要使用
\\
对Windows样式路径中的反斜杠进行转义,因为单个反斜杠表示转义字符,例如换行符为\n
,制表符为\t
正如@dawg所提到的,您还可以将
f
和r
组合在一起,这样python就不会转义任何字符 问题在于字符串中的反斜杠,而不是fstring格式。您需要使用\\
对Windows样式路径中的反斜杠进行转义,因为单个反斜杠表示转义字符,例如换行符为\n
,制表符为\t
正如@dawg所提到的,您还可以将
f
和r
组合在一起,这样python就不会转义任何字符 正如tiega提到的,您遇到的问题是构建f字符串时的\
作为一种更为坚实的方法,您可以考虑使用操作路径。 示例:
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
正如tiega提到的,您遇到的问题是构建f字符串时的
\
作为一种更为坚实的方法,您可以考虑使用操作路径。 示例:
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
尝试将所有“\”替换为“\”。或者,保留
“\”
,但在字符串前面使用fr
组合原始字符串和格式化字符串。这就是为什么我们尝试将所有“\”替换为“\”。或者,保留“\”
到位,但在字符串前面使用fr
组合原始字符串和格式化字符串。这就是为什么您可能希望提到有一组f字符串可以避免此问题…您可能希望提到有一组f字符串可以避免此问题…一件事,如果我需要使用此斜杠生成路径,该怎么办“/”?在Windows上,/
字符是文件名字符。有一件事,如果我需要用斜杠“/”生成路径,该怎么办?/
字符是Windows上的文件名字符。