Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

python - Strange path separators on Windows

I an running 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:workKindlesrcsest1.html'
    document = loadFile(path)
    print len(document)

It gives me a trackback

D:workKindleTests>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\srcsest1.html'

D:workKindleTests>

If I change the path line to

path = 'D:workKindlesrcs\test1.html'

(note the double \) it all works fine.

Why? Either the separator is '' or it is not, not a mix?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to escape backslashes in paths with an extra backslash... like you've done for '\test1.html'.

'' is the escape sequence for a tab character.

'D:workKindlesrcsest1.html is essentially 'D:workKindlesrcs est1.html'.

You could also use raw literals, r'est1.html' expands to:

'\test1.html'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...