Windows 中的 Python 长文件名支持中断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1365797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python long filename support broken in Windows
提问by Sophy
I write Python script to copy files; unfortunately it keeps failing because filename is too long(>256). Is there anyway to deal with that problem?
我编写了 Python 脚本来复制文件;不幸的是,它一直失败,因为文件名太长(> 256)。有没有办法解决这个问题?
I'm using Python 2.5.4 and Windows XP.
我使用的是 Python 2.5.4 和 Windows XP。
Cheers,
干杯,
回答by bcat
回答by Martin v. L?wis
In order to use the \\?\
prefix (as already proposed), you also need to make sure you use Unicode strings as filenames, not regular (byte) strings.
为了使用\\?\
前缀(正如已经提出的那样),您还需要确保使用 Unicode 字符串作为文件名,而不是常规(字节)字符串。
回答by Helga
For anyone else looking for solution here:
对于在此处寻找解决方案的其他人:
- You need to add prefix
\\?\
as already stated, and make sure string is unicode; - If you are using shutil, especially something like shutil.rmtree with onerror method, you'll need to modify it too to add prefix as it gets stripped somewhere on the way.
- 您需要添加
\\?\
前面已经说过的前缀,并确保字符串是 unicode; - 如果您使用的是shutil,尤其是带有onerror 方法的shutil.rmtree 之类的东西,您还需要修改它以添加前缀,因为它在途中的某个地方被剥离了。
You'll have to write something like:
你必须写这样的东西:
def remove_dir(directory):
long_directory = '\\?\' + directory
shutil.rmtree(long_directory, onerror=remove_readonly)
def remove_readonly(func, path, excinfo):
long_path = path
if os.sep == '\' and '\\?\' not in long_path:
long_path = '\\?\' + long_path
os.chmod(long_path, stat.S_IWRITE)
func(long_path)
This is an example for Python 3.x so all strings are unicode.
这是 Python 3.x 的示例,因此所有字符串都是 unicode。
回答by Alex Martelli
Have you tried the workarounds suggested in thisold thread, exp. the "magic prefix" trick? I don't know if the underyling issue (that we're not using the right one out of the many available Windows APIs for files) ever got fixed, but the workarounds should work...
您是否尝试过这个旧线程 exp 中建议的解决方法?“魔法前缀”的把戏?我不知道底层问题(我们没有在许多可用的 Windows API 中使用正确的文件)是否得到修复,但解决方法应该有效......