Ben Mayo
Ben Mayo

Reputation: 1315

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

Upvotes: 1

Views: 91

Answers (2)

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

'\' 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'

Upvotes: 1

Yann Vernier
Yann Vernier

Reputation: 15877

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.

Upvotes: 2

Related Questions