windows and file names > 256 bytes

Albert-Jan Roskam sjeik_appie at hotmail.com
Fri Jun 26 13:48:54 EDT 2015


On Thu, 25 Jun 2015 14:37:55 +0100, Tim Golden wrote:

> On 25/06/2015 14:35, Michael Torrie wrote:
>> On 06/25/2015 06:34 AM, Tim Golden wrote:
>>> On 25/06/2015 13:04, Joonas Liik wrote:
>>>> It sounds to me more like it is possible to use long file names on
>>>> windows but it is a pain and in python, on windows it is basically
>>>> impossible.
>>>
>>> Certainly not impossible: you could write your own wrapper function:
>>>
>>> def extended_path(p):
>>>     return r"\\?\%s" % os.path.abspath(p)
>>>
>>> where you knew that there was a possibility of long paths and that an
>>> absolute path would work.
>> 
>> The OP mentions that even when he manually supplies extended paths,
>> os.mkdir, os.getsize, and shutil.rmtree return errors for him in Python
>> 2.7.  So there's more to this problem.
>> 
>> 
> He's probably not passing unicode strings: the extended path only works
> for unicode string. For 3.x that's what you do by default.

Hi all,

Thanks for your replies. I've been messing with this a bit more. I 
created a little test script (see below). However, this only works with 
drive letters, not with UNC paths. I tried using os.chdir, DOS pushd, 
subst, net use but they all don't seem to work with with looooong paths. 
I finally managed to remove an absurdly long dir with shutil.rmtree, 
after changing sys.setrecursionlimit. But my main goal was to get the 
file size (and, actually, also the file owner) of a long file name on XP.

import os
import shutil
import sys
 
# create an insanely long directory tree
p = os.getenv("TEMP")
#p = ur"\\server\share\blah\temp"
tmpdir = p
os.chdir(tmpdir)
for i in xrange(1000):
    tmpdir = os.path.join(tmpdir, "sub")
    os.mkdir("\\\\?\\" + tmpdir)
    #os.mkdir(u"\\\\?\\UNC" + tmpdir[1:])
 
# write a file to it
deep = "\\\\?\\" + os.path.join(tmpdir, "deep.txt")
assert os.path.exists(deep)
with open(deep, "w") as f:
    f.write("Deep!\r\n")
 
# try if the file size can be determined (requires special \\?\ notation)
print "@@@@ %d bytes" % os.path.getsize(deep)
 
# now delete the whole directory and its contents.
path = "\\\\?\\" + os.path.join(p, "sub")
path = path.decode(sys.getfilesystemencoding())
sys.setrecursionlimit(10 ** 7)  # net use, pushd, subst will not work
shutil.rmtree(path)

Any feedback is welcome. I will post the solution somewhere so somebody 
else will be spared this nuisance. :-)

Regards,
Albert-Jan


---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus





More information about the Python-list mailing list