我有文件夹/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')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句