Python - Windows maximum directory path length workaround

前端 未结 2 1287
终归单人心
终归单人心 2021-01-24 02:26

The problem is the character limit for the path in windows when creating multiple directories using pythons os.makedirs()

I found this post when searching f

相关标签:
2条回答
  • 2021-01-24 02:26

    you need to use unc path and unicode filenames, but not all python functions are aware of this, os.mkdir works while os.makedirs not

    import os
    
    path = u'\\\\?\\c:\\'
    
    for i in xrange(1000):
        path += u'subdir\\'
        os.mkdir(path)
    

    but it's better to give also the code to remove them, windows explorer is unable to delete

    import os
    
    path = u'\\\\?\\c:\\'
    
    for i in xrange(1000, 0, -1):
        try:
            os.rmdir(path + (u'subdir\\' * i))
        except:
            pass
    
    0 讨论(0)
  • 2021-01-24 02:29

    Per this stackoverflow answer: while chdir can go up one directory with os.chdir(".."), the platform-agnostic way is: os.chdir(os.pardir).

    Either call this N times in a loop;
    or try an unreadable one-liner like this (untested):
    os.chdir(os.path.join(*([os.pardir] * NUM_TIMES)))

    (Instead of path.split('/'), you could also use the method described here for it to work on all operating systems)

    0 讨论(0)
提交回复
热议问题