I have a dictionary:
my_dictionary = {"058498":"table", "064165":"pen", "055123":"pencil"}
I iterate over it:
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() )
But I get this error:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\user\\Desktop\\File_055123.pdf'
It can't find my file. Why does it think there are double backslashes in file path?
解决方案
The double backslash is not wrong, python prints/represents it that to the user way. If a = r'raw s\tring' and b = 'raw s\\tring' (no 'r' and explicit double slash) then they are both represented as 'raw s\\tring'.
>>> a = r'raw s\tring'
>>> b = 'raw s\\tring'
>>> a
'raw s\\tring'
>>> b
'raw s\\tring'
Btw, your code is clearly edited and mismatched between the actual and what you posted since there's an obvious difference in the error message and the filename:
You have:
PDF = r'C:\Users\user\Desktop\File_%s.pdf' %item
but the output shows:
'C:\\Users\\user\\Desktop\\Filed_055123.pdf'
Note the extra d in the file name Filed_ vs File_. The error message may be coming from the part you've edited.