python 文件路径斜杠变成两道,如何摆脱python windows文件路径字符串中的双反斜杠?...

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值