Unable to locate files with long names on Windows with Python

前端 未结 3 1876
囚心锁ツ
囚心锁ツ 2020-12-08 19:21

I need to walk through folders with long file names in Windows.

I tried using os.listdir(), but it crashes with long pathnames, which is bad.

I

3条回答
  •  感动是毒
    2020-12-08 20:13

    Use the 8.3 fallback to avoid the long pathname, browsing in Win7 explorer this seems to be what windows itself does, ie every long paths has a shorter 'true name':

    >>> long_unc="\\\\K53\\Users\\Tolan\\testing\\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\xxxxxxxxxxxxxxxxxxxxxxxxffffdffffdffffdffffdffffdffffdffffdwgggggggggggggggggggggggggggggggggggxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\esssssssssssssssssssssggggggggggggggggggggggggggggggggggggggggggggggeee"
    >>> os.listdir(long_unc)
    FileNotFoundError: [WinError 3]
    

    but you can use win32api (pywin32) to 'build' up a shorter version, ie

    short_unc=win32api.GetShortPathName(win32api.GetShortPathName(win32api.GetShortPathName("\\\\K53\\Users\\Tolan\\testing\\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")+"\\xxxxxxxxxxxxxxxxxxxxxxxxffffdffffdffffdffffdffffdffffdffffdwgggggggggggggggggggggggggggggggggggxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") + "\\esssssssssssssssssssssggggggggggggggggggggggggggggggggggggggggggggggeee")
    >>> print(short_unc)
    \\K53\Users\Tolan\testing\XXXXXX~1\XXXXXX~1\ESSSSS~1
    >>> import os
    >>> os.listdir(short_unc)
    ['test.txt']
    

    clearly you can just fold the win32api.GetShortPathName call into you dir exploration rather than nesting as in my example. I've done it like this with 3 calls because if you've already got a 'too long' path then win32api.GetShortPathName wont cope with it either, but you can do it per dir and stay below the limit.

提交回复
热议问题