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
275 views
in Technique[技术] by (71.8m points)

Long paths in Python on Windows

I have a problem when programming in Python running under Windows. I need to work with file paths, that are longer than 256 or whatsathelimit characters. Now, I've read basically about two solutions:

  1. Use GetShortPathName from kernel32.dll and access the file in this way.

That is nice, but I cannot use it, since I need to use the paths in a way

shutil.rmtree(short_path)

where the short_path is a really short path (something like D:oolsEclipse) and the long paths appear in the directory itself (damn Eclipse plugins).

  1. Prepend "\\?" to the path

I haven't managed to make this work in any way. The attempt to do anything this way always result in error WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: <path here>

So my question is: How do I make the 2nd option work? I stress that I need to use it the same way as in the example in option #1.

OR

Is there any other way?

EDIT: I need the solution to work in Python 2.7

EDIT2: The question Python long filename support broken in Windows does give the answer with the 'magic prefix' and I stated that I know it in this question. The thing I do not know is HOW do I use it. I've tried to prepend that to the path but it just failed, as I've written above.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Well it seems that, as always, I've found the answer to what's been bugging me for a week twenty minutes after I seriously ask somebody about it.

So I've found that I need to make sure two things are done correctly:

  1. The path can contain only backslashes, no forward slashes.
  2. If I want to do something like list a directory, I need to end the path with a backslash, otherwise Python will append /*.* to it, which is a forward slash, which is bad.

Hope at least someone will find this useful.


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

...