在Python中使用os.path.expandvars时,我在访问Document文件夹或AppData文件夹时没有遇到太多问题,但当尝试访问桌面文件夹时,系统抛出以下错误。
是否需要另一个变量,或者桌面与其他位置之间是否真的需要双重转义"\ \“?
if os.path.exists(os.path.join(os.path.expandvars("%userprofile%"),"Desktop"))==True:
print("yes")
#No issue with this: returns True
if os.path.exists(os.path.join(os.path.expandvars("%userprofile%"),"Desktop\NF"))==True:
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 7-8: malformed \N character escape #Need help understanding why an escape is needed for this location
^
if os.path.exists(os.path.join(os.path.expandvars("%userprofile%"),"Documents\Videos"))==True: print("yes") #No issue with this: returns True
桌面文件夹NF确实存在,并且在尝试使用代码访问之前已经存在。
发布于 2020-04-16 00:58:19
Python使用\N序列表示由其名称标识的unicode字符:
print('\N{LATIN CAPITAL LETTER A}')
A
因此,如果字符串包含没有开始'\N{name}'
转义的序列'\N'
,则会引发SyntaxError
,除非'\N'
被转义:
'Deskstop\\New'
或者是原始字符串的一部分。
r'Deskstop\New'
或者,如果反斜杠是路径分隔符,则替换为正斜杠
'Desktop/New'
我怀疑如果这样使用,os.path.join
或它的pathlib
等效物将正确处理这种情况:
os.path.join(os.path.expandvars("%userprofile%"),"Desktop", "New")
但我不能100%确定,因为我不是在Windows机器上。
https://stackoverflow.com/questions/61233237
复制相似问题