[英]Understanding Backslash Behaviour (Windows)
我宣布变量'path'
path = "C:\\dir\\file.zip"
因为第一个斜线逃脱了第二个,所以
print path
>>>C:\dir\file.zip
但是,当我尝试解压缩文件时
inF = gzip.GzipFile(path, 'rb')
我收到了错误
IOError: [Errno 2] No such file or directory: 'C:\\dir\\file.gz'
这些额外的反斜杠是如何出现的,我该如何解决?
TIA
那些额外的反斜杠是为了使字符串明确,因为它可能包含引号,换行符等。 IOError已经打印了字符串的repr
形式,这样可以通过将其复制到Python代码中来重新创建该值:
>>> path = "C:\\dir\\file.zip"
>>> print path
C:\dir\file.zip
>>> print repr(path)
'C:\\dir\\file.zip'
所以额外的反斜杠就像你在第一时间所做的一样,并且对错误本身没有影响。
'\\'用于消除任何字符的特殊含义,如''
或""
或'\\'和manu其他。
rawstring
为你做同样的事情
代替
path = "C:\\dir\\file.zip"
path = r'C:\dir\file.zip'
>>> print 'C:\\dir\\file.zip'
C:\dir\file.zip
>>> print (r'C:\Users\dir\file.zip')
C:\dir\file.zip
>>> print (ur'C:\\Users\dir\file.zip') #ur'' as unicode string literals with \u or \U sequences are broken in python2 and several backslashes are treated as one on windows
使用正斜杠rahter比反斜杠
>>> a = 'C:/User/dir/file.zip'
>>> a
'C:/User/dir/file.zip'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.