我声明variables'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
使用向后斜杠比向后斜杠
>>> a = 'C:/User/dir/file.zip' >>> a 'C:/User/dir/file.zip'