简体   繁体   English

了解反斜杠行为(Windows)

[英]Understanding Backslash Behaviour (Windows)

I declare variable 'path' 我宣布变量'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 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: IOError已经打印了字符串的repr形式,这样可以通过将其复制到Python代码中来重新创建该值:

>>> 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. '\\'用于消除任何字符的特殊含义,如''""或'\\'和manu其他。

rawstring do the same for you check here rawstring为你做同样的事情

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 使用正斜杠rahter比反斜杠

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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