如何摆脱 python windows 文件路径字符串中的双反斜杠?[重复]
- 2025-02-25 09:07:00
- admin 原创
- 19
问题描述:
我有一本字典:
my_dictionary = {"058498":"table", "064165":"pen", "055123":"pencil"}
我反复思考:
for item in my_dictionary:
PDF = r'C:Users/userDesktopFile_%s.pdf' %item
doIt(PDF)
def doIt(PDF):
part = MIMEBase('application', "octet-stream")
part.set_payload( open(PDF,"rb").read() )
但是我收到此错误:
IOError: [Errno 2] No such file or directory: 'C:\\Users\/user\\Desktop\\File_055123.pdf'
它找不到我的文件。为什么它认为文件路径中有双反斜杠?
解决方案 1:
双反斜杠并没有错,python向用户表示的\
方式就是这样的。在每个双反斜杠中,第一个会转义第二个以表示实际的反斜杠。如果a = r'raw s ring'
和b = 'raw s\tring'
(没有 'r' 和显式双斜杠),则它们都表示为'raw s\tring'
。
>>> a = r'raw s ring'
>>> b = 'raw s\\tring'
>>> a
'raw s\\tring'
>>> b
'raw s\\tring'
为了澄清起见,当您打印字符串时,您会看到它的用法,就像在路径中一样 - 只有一个反斜杠:
>>> print(a)
raw s ring
>>> print(b)
raw s ring
在这个打印字符串的情况下,
并不意味着制表符,而是一个反斜杠``后跟字母“t”。
否则,没有“r”前缀且只有一个反斜杠的字符串会转义其后的字符,从而使得它评估其后跟的“t”==tab:
>>> t = 'not raw s ring' # here ' ' = tab
>>> t
'not raw s ring'
>>> print(t) # will print a tab (and no letter 't' in 's ring')
not raw s ring
因此在 PDF 路径+名称中:
>>> item = 'xyz'
>>> PDF = r'C:Users/userDesktopFile_%s.pdf' % item
>>> PDF # the representation of the string, also in error messages
'C:\\Users\/user\\Desktop\\File_xyz.pdf'
>>> print(PDF) # "as used"
C:Users/userDesktopFile_xyz.pdf
有关转义序列的更多信息,请参阅此处的表格。另请参阅__str__
vs。__repr__
解决方案 2:
双反斜杠是由于r
,原始字符串:
r'C:Users/userDesktopFile_%s.pdf' ,
使用它是因为``可能会转义某些字符。
>>> strs = "c:desktop
otebook"
>>> print strs #here print thinks that
in
otebook is the newline char
c:desktop
otebook
>>> strs = r"c:desktop
otebook" #using r'' escapes the \n>>> print strs
c:desktop
otebook
>>> print repr(strs) #actual content of strs
'c:\\desktop\\notebook'
解决方案 3:
为了避免头痛,您也可以使用其他斜线。如果您明白我的意思。看起来相反的斜线。
你现在正在使用PDF = 'C:Users/userDesktopFile_%s.pdf' %item
尝试使用**
PDF = 'C:/Users/user/Desktop/File_%s.pdf' %item
** 它不会被视为转义字符。
解决方案 4:
不是。双反斜杠只是计算机表示反斜杠的方式。是的,我知道这听起来很奇怪,但请这样想 - 为了表示特殊字符,反斜杠被选为转义字符(例如 \n 表示换行符,而不是反斜杠字符后跟 n 字符)。但是,如果您实际上想要打印(或使用)反斜杠(可能后跟更多字符),但您不想让计算机将其视为转义字符,会发生什么?在这种情况下,我们对反斜杠本身进行转义,这意味着我们使用双反斜杠,以便计算机将理解它是一个单反斜杠。
由于r
您在字符串前面添加了,所以在您的情况下它会自动完成。
解决方案 5:
alwbtc @我敢说:“我发现了这个漏洞……”
代替
PDF = r'C:Users/userDesktopFile_%s.pdf' %item
doIt(PDF)`
和
for item in my_dictionary:
PDF = r'C:Users/userDesktopFile_%s.pdf' % mydictionary[item]
doIt(PDF)`
事实上,您真正寻找的是 File_pencil.pdf(而不是 File_055123.pdf)。您滑动的是索引字典,而不是其内容。这个论坛主题可能是一种副作用。