Python-创建一个子目录包含父目录中的所有目录和文件
我想创建一个子目录包含父目录中的所有目录和文件。
例如: 存在父级目录及其子目录和文件。
/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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
shutil.copytree
是递归将目录树复制到新位置的常用方法,并且它具有是否在现有目录上出现错误,遵循Symlinks等等。但是,并发症是您的目的地是源内部的,这意味着任何递归方法最终都可能开始重新修复新创建的树作为源的一部分Ad Infinitum。
管理此问题的最安全方法是将您的关注目录复制到IT的某些临时目录外部,然后从该中间位置复制到目的地:
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: