如何在Python Windows文件路径字符串中删除双斜杠?

2024-06-09 23:08:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典:

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'

找不到我的档案。为什么它认为文件路径中有双反斜杠?


Tags: dictionary字典pdfmytableitemusersfile
3条回答

不是的。双反斜杠只是计算机说反斜杠的方式。是的,我知道这听起来很奇怪,但是这样想-为了表示特殊字符,反斜杠被选为转义字符(例如,n表示换行符,而不是反斜杠字符后跟n字符)。但是,如果您确实想打印(或使用)反斜杠(可能后面跟着更多字符),但不希望计算机将其视为转义字符,会发生什么情况?在这种情况下,我们对反斜杠本身进行转义,这意味着我们使用双反斜杠,这样计算机就可以理解它是单反斜杠。

这在您的情况下是自动完成的,因为您在字符串前面添加了r

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

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

>>> print(a)
raw s\tring
>>> print(b)
raw s\tring

在这种打印字符串的情况下,\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

所以在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

有关escape sequences in the table here的详细信息。另请参见^{} vs ^{}

双反斜杠是由于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'

相关问题 更多 >