如何摆脱python windows文件路径字符串中的双反斜杠? [英] How to get rid of double backslash in python windows file path string?
问题描述
我有一个字典:
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'
找不到我的文件。为什么它认为文件路径中有双反斜杠?
It can't find my file. Why does it think there are double backslashes in file path?
推荐答案
双反斜杠没有错,python打印/表示它以用户的方式。如果 a = r'raw s\tring'
和 b ='raw s\\\tring'
(没有'r'和明确的双斜杠),那么它们都表示为'raw s\\\tring'
。
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,您的代码已清晰编辑由于错误信息和文件名之间存在明显的差异:
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:
您有:
PDF = r'C:\Users\user\Desktop\File_%s.pdf' %item
但输出显示:
'C:\\Users\\user\\Desktop\\Filed_055123.pdf'
请注意文件名中的额外 d 文件_
vs 文件_
。错误信息可能来自您编辑的部分。
Note the extra d in the file name Filed_
vs File_
. The error message may be coming from the part you've edited.
这篇关于如何摆脱python windows文件路径字符串中的双反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!