如何摆脱python windows文件路径字符串中的双反斜杠?

alw*_*btc 23 python dictionary file path

我有一本字典:

my_dictionary = {"058498":"table", "064165":"pen", "055123":"pencil"}
Run Code Online (Sandbox Code Playgroud)

我迭代它:

for item in my_dictionary:
    PDF = r'C:\Users\user\Desktop\File_%s.pdf' %item
    doIt(PDF)

def doIt(PDF):
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(PDF,"rb").read() )
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\user\\Desktop\\File_055123.pdf'
Run Code Online (Sandbox Code Playgroud)

它无法找到我的文件.为什么它认为文件路径中有双反斜杠?

ane*_*oid 15

双反斜杠没有错,python 代表它对用户的方式.在每个双反斜杠中\\,第一个逃脱第二个反映意味着实际的反斜杠.如果a = r'raw s\tring'b = 'raw s\\tring'(没有'r'和显式双斜线)那么它们都表示为'raw s\\tring'.

>>> a = r'raw s\tring'
>>> b = 'raw s\\tring'
>>> a
'raw s\\tring'
>>> b
'raw s\\tring'
Run Code Online (Sandbox Code Playgroud)

为了澄清,当你打印字符串时,你会看到它会被使用,就像在路径中一样 - 只有一个反斜杠:

>>> print(a)
raw s\tring
>>> print(b)
raw s\tring
Run Code Online (Sandbox Code Playgroud)

在这个打印的字符串的情况下,\t并不意味着一个标签,它是一个反斜杠\后跟字母't'.

否则,没有'r'前缀和单个反斜杠的字符串将在其后转义字符,使其评估它后面的't'== tab:

>>> t = 'not raw s\tring'  # here '\t' = tab
>>> t
'not raw s\tring'
>>> print(t)  # will print a tab (and no letter 't' in 's\tring')
not raw s       ring
Run Code Online (Sandbox Code Playgroud)

所以在PDF路径+名称中:

>>> item = 'xyz'
>>> PDF = r'C:\Users\user\Desktop\File_%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\user\Desktop\File_xyz.pdf
Run Code Online (Sandbox Code Playgroud)

有关此表中的转义序列的更多信息.另请参阅__str__VS__repr__.

  • 对不起,但这不是一个有用的答案.所以,如果是双斜线,那么如何解决它???? (21认同)

Ash*_*ary 10

双反斜杠是由于r原始字符串:

r'C:\Users\user\Desktop\File_%s.pdf' ,
Run Code Online (Sandbox Code Playgroud)

使用它是因为\可能会逃避一些字符.

>>> strs = "c:\desktop\notebook"

>>> print strs                #here print thinks that \n in \notebook is the newline char
c:\desktop
otebook

>>> strs = r"c:\desktop\notebook"  #using r'' escapes the \
>>> print strs

c:\desktop\notebook

>>> print repr(strs)   #actual content of strs
'c:\\desktop\\notebook'
Run Code Online (Sandbox Code Playgroud)