Python-创建一个子目录包含父目录中的所有目录和文件

发布于 2025-01-26 04:14:50 字数 741 浏览 4 评论 0原文

我想创建一个子目录包含父目录中的所有目录和文件。

例如: 存在父级目录及其子目录和文件。

/parent
    /parent/child1
        /parent/child1/a.txt
        /parent/child1/b.txt
    /parent/child2
        /parent/child2/child2-1
            /parent/child2/child2-1/c.txt
        /parent/child2/child2/d.txt
    /parent/e.txt

我的目标是:创建一个名为“新”的子目录,其中包含父目录中的所有目录和文件。:

/parent
    /parent/new
        /parent/new/child1
            /parent/new/child1/a.txt
            /parent/new/child1/b.txt
        /parent/new/child2
            /parent/new/child2/child2-1
                /parent/new/child2/child2-1/c.txt
            /parent/new/child2/child2/d.txt
        /parent/new/e.txt

是否有一种Pythonic方法可以满足我的需求?

谢谢!

I want to create a subdirectory contains all directories and files in the parent directory.

For example:
There exists a parent directory and its subdirectories and files.

/parent
    /parent/child1
        /parent/child1/a.txt
        /parent/child1/b.txt
    /parent/child2
        /parent/child2/child2-1
            /parent/child2/child2-1/c.txt
        /parent/child2/child2/d.txt
    /parent/e.txt

My Target: Create a subdirectory called "new" that contains all directories and files in the parent directory.:

/parent
    /parent/new
        /parent/new/child1
            /parent/new/child1/a.txt
            /parent/new/child1/b.txt
        /parent/new/child2
            /parent/new/child2/child2-1
                /parent/new/child2/child2-1/c.txt
            /parent/new/child2/child2/d.txt
        /parent/new/e.txt

Is there a Pythonic way to meet my needs?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不必了 2025-02-02 04:14:51

shutil.copytree是递归将目录树复制到新位置的常用方法,并且它具有是否在现有目录上出现错误,遵循Symlinks等等。

但是,并发症是您的目的地是源内部的,这意味着任何递归方法最终都可能开始重新修复新创建的树作为源的一部分Ad Infinitum。

管理此问题的最安全方法是将您的关注目录复制到IT的某些临时目录外部,然后从该中间位置复制到目的地:

import tempfile, shutil
with tempfile.TemporaryDirectory() as temp:
    temp_new = temp + '/new'
    shutil.copytree('..', temp_new)
    shutil.copytree(temp_new, 'new')

shutil.copytree is the usual way to recursively copy a directory tree to a new location, and it has options for whether to error out on existing directories, follow symlinks, and so on.

The complication, however, is that your destination is inside of the source, meaning that any recursive approach may end up beginning to re-copy the newly created tree as part of the source, ad infinitum.

The safest way to manage this is to copy your directory of interest to some temporary directory outside of it, and then copy from that intermediate location to the destination:

import tempfile, shutil
with tempfile.TemporaryDirectory() as temp:
    temp_new = temp + '/new'
    shutil.copytree('..', temp_new)
    shutil.copytree(temp_new, 'new')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文