Question

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?

I'm using Python 2.5.4 and Windows XP.

Cheers,

Was it helpful?

OTHER TIPS

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.

Have you tried the workarounds suggested in this old 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...

For anyone else looking for solution here:

  1. You need to add prefix \\?\ as already stated, and make sure string is unicode;
  2. 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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top