了解反斜杠行为(Windows)中

问题描述:

我声明变量“路径”了解反斜杠行为(Windows)中

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

+0

出现其他反斜杠,因为错误消息使用传递给它的路径的“repr”版本。 – 2014-11-21 12:48:47

+1

更简单的方法是用正斜杠替换反斜杠。 Windows和Linux都应该使用正斜杠。 – HashSplat 2014-11-21 13:20:14

+0

@JustinEngel改变斜杠不会*解释*情况。毕竟,问题是关于*理解*发生了什么。通过使用不同的斜杠来避免它并没有帮助。 – poke 2014-11-21 13:27:57

这些额外的反斜线就在那儿串明确的,因为它可能包含引号,换行符等。 IO错误已打印的repr形式的字符串,使得该值可以通过复制到Python代码来重新创建:

>>> path = "C:\\dir\\file.zip" 
>>> print path 
C:\dir\file.zip 
>>> print repr(path) 
'C:\\dir\\file.zip' 

所以额外的反斜线只是相同逃逸你在第一时间做了,没有影响错误本身。

“\”用来消失任何字符的特殊含义等''""或“\”和Manu其他。

rawstring做同样为您check here

代替

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' 
+0

他们是完全一样的东西。 – 2014-11-21 12:47:34

+0

Python 2原始unicode字符串被破坏。试试'ur“\ Users”' – 2014-11-21 13:03:14

+0

@SmitJohnth在python2'str'中使用bytestring,这里给出了bytestring,所以我认为不用担心unicode在这里,但感谢我的建议我更新我的代码。 – 2014-11-21 13:05:41