简体   繁体   中英

Understanding Backslash Behaviour (Windows)

I declare variable 'path'

path = "C:\\dir\\file.zip"

Because the first slash escapes the second, and so

print path
>>>C:\dir\file.zip

However, when I try to unzip the file

inF = gzip.GzipFile(path, 'rb')

I get the error

IOError: [Errno 2] No such file or directory: 'C:\\dir\\file.gz'

How are these additional backslashes appearing, and how can I fix it?

TIA

Those additional backslashes are there to make the string unambiguous, as it might have contained quotes, newlines and such. IOError has printed the repr form of the string, such that the value can be recreated by copying it into Python code:

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

So the extra backslashes are simply the same escaping you did in the first place, and have no impact on the error itself.

'\\' is used to vanish the special meaning of any character like '' or "" or '\\' and manu other.

rawstring do the same for you check here

instead

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

Use forward slashes rahter than backward slashes

   >>> a = 'C:/User/dir/file.zip'
   >>> a
    'C:/User/dir/file.zip'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM