复制没有父文件夹的子文件夹

copy subfolder without parent folders

我有文件夹 /a/b/c/d/,我想将 d/ 复制到目标 /dst/

然而,shutil.copytree("/a/b/c/d", "/dst") 产生 /dst/a/b/c/d

我只要/dst,甚至/dst/d就够了,但我不想要所有的中间文件夹。

[编辑]

正如其他人所指出的,copytree 做我想做的事——我无意中将源的完整路径添加到我的目的地!

这就是 shutil.copytree 所做的!

shutil.copytree 递归地将整个目录树 以 src 为根复制到名为 dst

的目录

所以问题中的陈述:

shutil.copytree("/a/b/c/d", "/dst") 产生 /dst/a/b/c/d.

只是wrong.this会将d(和子目录)的内容复制到/dst

鉴于此文件结构(在我的目录 /tmp 上):

a
└── b
    └── c
        └── d
            ├── d_file1
            ├── d_file2
            ├── d_file3
            └── e
                ├── e_file1
                ├── e_file2
                └── e_file3

如果你这样做 shutil.copytree("/tmp/a", "/tmp/dst") 你将得到:

dst
└── b
    └── c
        └── d
            ├── d_file1
            ├── d_file2
            ├── d_file3
            └── e
                ├── e_file1
                ├── e_file2
                └── e_file3

但是如果你这样做 shutil.copytree('/tmp/a/b/c/d', '/tmp/dst/d') 你会得到:

dst
└── d
    ├── d_file1
    ├── d_file2
    ├── d_file3
    └── e
        ├── e_file1
        ├── e_file2
        └── e_file3

shutil.copytree('/tmp/a/b/c/d', '/tmp/dst')

dst
├── d_file1
├── d_file2
├── d_file3
└── e
    ├── e_file1
    ├── e_file2
    └── e_file3

shutil.copytree 也采用相对路径。你可以这样做:

import os
os.chdir('/tmp/a/b/c/d')    
shutil.copytree('.', '/tmp/dst')

或者,since Python 3.6, you can use pathlib 参数做:

from pathlib import Path
p=Path('/tmp/a/b/c/d')
shutil.copytree(p, '/tmp/dst')

无论哪种情况,您都会得到与 shutil.copytree('/tmp/a/b/c/d', '/tmp/dst')

相同的结果