Windows上的奇怪路径分隔符 [英] Strange path separators on Windows
问题描述
我正在运行此代码:
#!/usr/bin/python coding=utf8
# test.py = to demo fault
def loadFile(path):
f = open(path,'r')
text = f.read()
return text
if __name__ == '__main__':
path = 'D:\work\Kindle\srcs\test1.html'
document = loadFile(path)
print len(document)
它给了我一个引用
D:\work\Kindle\Tests>python.exe test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
document = loadFile(path)
File "test.py", line 5, in loadFile
f = open(path,'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'D:\\work\\Kindle\\srcs\test1.html'
D:\work\Kindle\Tests>
如果我将路径行更改为
path = 'D:\work\Kindle\srcs\\test1.html'
(请注意双\\),一切正常.
(note the double \\) it all works fine.
为什么?分隔符是'\'还是不是,不是混合?
Why? Either the separator is '\' or it is not, not a mix?
系统. Windows 7、64位, Win32上的Python 2.7(r27:82525,2010年7月4日,09:01:59)[MSC v.1500 32位(Intel)]
System. Windows 7, 64bit, Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
已选中-所有反斜杠均正确显示.
Checked - and all the backslashes appear correctly.
推荐答案
当下一个字符组合产生特殊含义时,反斜杠是转义字符.请看以下示例:
The backslash is an escape character when the next character combination would result in a special meaning. Take the following examples:
>>> '\r'
'\r'
>>> '\n'
'\n'
>>> '\b'
'\x08'
>>> '\c'
'\\c'
>>>
当
r,n和b都带有反斜杠时,都具有特殊含义.对于t同样如此,这将产生一个制表符.您可能需要A.将所有反斜杠加倍以保持一致性,因为'\\'
会产生一个反斜杠,或者B使用原始字符串:r'c:\path\to\my\file.txt'
.前面的r会提示解释器不要将反斜杠评估为转义序列,从而防止\t
出现在制表符中.
r, n, and b all have special meanings when preceded by a backslash. The same is true for t, which would produce a tab. You either need to A. Double all your backslashes, for consistency, because '\\'
will produce a backslash, or, B, use raw strings: r'c:\path\to\my\file.txt'
. The preceding r will prompt the interpreter not to evaluate back slashes as escape sequences, preventing the \t
from appearing as a tab.
这篇关于Windows上的奇怪路径分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!