我有文件夹/a/b/c/d/
,我想复制d/
到目的地/dst/
。
但是,shutil.copytree("/a/b/c/d", "/dst")
产生/dst/a/b/c/d
.
我只想要/dst
,甚至/dst/d
就足够了,但我不想要所有的中间文件夹。
[编辑]
正如其他人所指出的,copytree 做了我想做的事——我无意中将源的完整路径添加到了我的目的地!
我有文件夹/a/b/c/d/
,我想复制d/
到目的地/dst/
。
但是,shutil.copytree("/a/b/c/d", "/dst")
产生/dst/a/b/c/d
.
我只想要/dst
,甚至/dst/d
就足够了,但我不想要所有的中间文件夹。
[编辑]
正如其他人所指出的,copytree 做了我想做的事——我无意中将源的完整路径添加到了我的目的地!
鉴于此文件结构(在我的目录上/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')
或者,从 Python 3.6 开始,您可以使用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')
那是什么shutil.copytree
!
shutil.copytree 递归地复制以 src 为根的整个目录树到名为 dst 的目录
所以问题中的陈述:
shutil.copytree("/a/b/c/d", "/dst")
产生/dst/a/b/c/d
.
是错误的。这会将d
(和子目录)的内容复制到/dst