2012-08-12 133 views
19

我有一本字典:如何摆脱python windows文件路径字符串中的双反斜杠?

my_dictionary = {"058498":"table", "064165":"pen", "055123":"pencil"} 

我遍历它:

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()) 

但我得到这个错误:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\user\\Desktop\\File_055123.pdf' 

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

+3

只有一个反斜杠。你看到了字符串表示。该文件不存在。 – 2012-08-12 18:36:14

+2

双反斜杠没有错,python打印/表示它对用户的方式。如果a = r'raw s \ tring''和'b ='raw s \\ tring''(不'r'和明确的双斜杠),那么它们都被表示为'raw s \'tring''。 – aneroid 2012-08-12 18:37:33

回答

14

双反斜杠没有错,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' 

顺便说一句,你的代码是清楚的编辑和实际的,哪些是你贴因为有错误消息的明显的区别和文件名之间的不匹配:

您有:

PDF = r'C:\Users\user\Desktop\File_%s.pdf' %item 

但输出显示:

'C:\\Users\\user\\Desktop\\Filed_055123.pdf' 

请注意文件名Filed_File_中额外的d。错误消息可能来自您编辑的部分。

+0

没有'd':''C:\\ Users \\ user \\ Desktop \\ File_055123.pdf'' – 2012-08-12 19:00:43

+0

现在可能已被编辑出来。 – aneroid 2012-08-13 16:49:30

+8

对不起,但这不是一个有用的答案。所以如果双斜杠的话,那么如何解决它? – DeeWBee 2016-07-06 19:34:05

9

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

r'C:\Users\user\Desktop\File_%s.pdf' , 

它是用来因为\可能逃跑的某些字符。

>>> 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' 
+0

在上面的例子中,如果你像'>>> strs'一样显示'strs',你应该得到'c:\\ desktop \\ notebook'。打印不显示转义,即双斜杠\\ – 2015-07-08 10:24:00

3

它没有。双反斜杠只是反斜杠电脑的一种方式。是的,我知道这听起来很奇怪,但是可以这样想 - 为了表示特殊字符,反斜杠被选为转义字符(例如,\ n表示换行符,而不是反斜杠字符后跟n个字符)。但是如果你真的想打印(或使用)一个反斜杠(可能后面跟着更多的字符),但是你不希望计算机把它当作逃避角色呢?在这种情况下,我们会避免反斜杠本身,这意味着我们使用双反斜杠,因此计算机将会理解它是单个反斜杠。

由于您在字符串前添加了r,所以会自动完成。

-1

alwbtc @ 我敢说: “我发现的bug ......”

更换

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

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

其实你真正需要的File_pencil.pdf (而不是File_055123.pdf)。 您正在滑动索引字典而不是其内容。 这个论坛话题可能是一个副作用。

3

除了头痛之外,您还可以使用其他斜线。 如果你知道我在说什么。相反的斜线。

你使用现在 PDF = 'C:\Users\user\Desktop\File_%s.pdf' %item

尝试使用 **

PDF = 'C:/Users/user/Desktop/File_%s.pdf' %item

** 它不会被视为转义字符。

相关问题