[英]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.