2014-11-21 51 views
1

我聲明變量「路徑」瞭解反斜槓行爲(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

回答

2

這些額外的反斜線就在那兒串明確的,因爲它可能包含引號,換行符等。 IO錯誤已打印的repr形式的字符串,使得該值可以通過複製到Python代碼來重新創建:

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

所以額外的反斜線只是相同逃逸你在第一時間做了,沒有影響錯誤本身。

1

「\」用來消失任何字符的特殊含義等''""或「\」和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