Strange Path Separators on Windows

I run this code:

#!/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)

It gives me a trackback

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>

If I changed the path line to

path = 'D:\work\Kindle\srcs\\test1.html'

(pay attention to double \\), everything works fine.

Why? Either the separator "\" or not, not a mix?

System. Windows 7, 64 bit, Python 2.7 (r27: 82525, July 4, 2010 09:01:59) [MSC v.1500 32 bit (Intel)] on win32

Checked - and all backslashes are displayed correctly.

+5
source share
6 answers

A backslash is an escape character when the next combination of characters results in a special value. 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 escape-, \t .

+6

Windows:

path = r'D:\work\Kindle\srcs\test1.html'

\t .

+6

... '\\test1.html'.

'\t' - escape- .

'D:\work\Kindle\srcs\test1.html 'D:\work\Kindle\srcs est1.html'.

, r'\test1.html' :

'\\test1.html'
+5

\ escape- Python. , D:\work\Kindle\srcs<tab>est1.html. os.sep, \\ , r'some text'.

+1

( r), ​​ os.path .

+1

Gotcha - The backslash in Windows file names contains an interesting overview.

0
source

All Articles