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'
(注意双\\),则一切正常。
为什么?分隔符要么是“\”,要么不是,不是混合?
系统。 Windows 7,64 位, Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Checked - 所有反斜杠都正确显示。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当下一个字符组合产生特殊含义时,反斜杠是转义字符。举个例子:
r、n 和 b 前面有反斜杠时都有特殊含义。 t 也是如此,它会产生一个制表符。为了保持一致性,您需要 A. 将所有反斜杠加倍,因为
'\\'
将生成反斜杠,或者 B,使用原始字符串:r'c:\path\to \my\file.txt'
。前面的 r 将提示解释器不要将反斜杠计算为转义序列,从而防止\t
显示为制表符。The backslash is an escape character when the next character combination would result in a special meaning. Take the following examples:
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.您需要使用额外的反斜杠转义路径中的反斜杠...就像您对
'\\test1.html'
所做的那样。'\t'
是制表符的转义序列。'D:\work\Kindle\srcs\test1.html
本质上是'D:\work\Kindle\srcs est1.html'
。您还可以使用原始文字,
r'\test1.html'
扩展为:You need to escape backslashes in paths with an extra backslash... like you've done for
'\\test1.html'
.'\t'
is the escape sequence for a tab character.'D:\work\Kindle\srcs\test1.html
is essentially'D:\work\Kindle\srcs est1.html'
.You could also use raw literals,
r'\test1.html'
expands to:对 Windows 路径使用原始字符串:
否则字符串的
\t
部分将被解释为制表符。Use raw strings for Windows paths:
Otherwise the
\t
piece of your string will be interpreted as a Tab character.反斜杠
\
是 转义字符。因此,您的实际文件路径将是D:\work\Kindle\srcsest1.html
。使用 os.sep,使用\\
转义反斜杠,或者通过r'some text'
使用原始字符串。The backslash
\
is an escape character in Python. So your actual filepath is going to beD:\work\Kindle\srcs<tab>est1.html
. Use os.sep, escape the backslashes with\\
or use a raw string by havingr'some text'
.除了使用原始字符串(带有 r 字符的前缀字符串)之外,os.path 模块可能有助于在构建路径名时自动提供操作系统正确的斜杠。
In addition to using a raw string (prefix string with the r character), the os.path module may be helpful to automatically provide OS-correct slashes when building a pathname.
陷阱 — Windows 中的反斜杠filenames 提供了一个有趣的概述。
Gotcha — backslashes in Windows filenames provides an interesting overview.