Python - Windows 最大目录路径长度解决方法 [英] Python - Windows maximum directory path length workaround

查看:57
本文介绍了Python - Windows 最大目录路径长度解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是使用pythons创建多个目录时windows中路径的字符限制os.makedirs()

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 for my problem before posting this:

​​python win32 文件名长度解决方法

现在选择的答案建议了前缀解决方法,但我的问题是,有没有办法确保 Windows 和 UNIX 中的功能?

Now the chosen answer suggests the prefix workaround but my question here is, is there a way to ensure functionality in Windows and UNIX?

我想到的另一种方法是一个一个创建文件夹,然后创建文件,这样就不会超过路径长度,但我无法弄清楚代码中的明显错误.

The other approach I thought of was to create the folders one by one and then create the file so that you never exceed the path length, but I can't figure out the obvious bug in the code.

path = ['folder1/s1/s1/abc.txt',
        'folder1/s1/s2/def.txt']

def makedirs(path):
    explode = path.split('/')
    for i in range(len(explode)-1):
        os.mkdir(explode[i])
        os.chdir(explode[i])

        if i == len(explode) -2:
            download_file(explode[i+1])

    # something to go back here
    os.chdir('../' * (len(explode)-3)) # ??


makedirs(path[0])

现在这仅适用于第一行,因为我不知道如何回到根目录或重置它.如果没有重置",文件夹就会相互关联:

Now this works for only the first line because I can't figure out how to get back to the root or reset it. Without the 'reset' the folders are being under each other:

folder1/s1/s1/folder1/s1/s1/abc.txt(或类似的东西)

我可以从 root 设置路径来重置它,但是我们可能会遇到达到最大长度的相同问题.任何有关如何在两个操作系统上运行的帮助将不胜感激!

I could set the path from root to reset it but then we might run into the same issue of reaching the max length. Any help on how to get this working on both OS would be appreciated!

请随时指出我的错误.

推荐答案

Per this stackoverflow answer: while chdir can go使用 os.chdir("..") 向上一级目录,与平台无关的方式是:os.chdir(os.pardir).

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

要么循环调用N次;
或尝试像这样不可读的单行(未经测试):
os.chdir(os.path.join(*([os.pardir] * NUM_TIMES)))

(代替 path.split('/'),​​您还可以使用 此处描述的方法适用于所有操作系统)

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

这篇关于Python - Windows 最大目录路径长度解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆