我终于想出了以下代码。它的作用几乎完全一样cp --parents
。
import os, shutil
def cp_parents(target_dir, files):
dirs = []
for file in files:
dirs.append(os.path.dirname(file))
dirs.sort(reverse=True)
for i in range(len(dirs)):
if not dirs[i] in dirs[i-1]:
need_dir = os.path.normpath(target_dir + dirs[i])
print("Creating", need_dir )
os.makedirs(need_dir)
for file in files:
dest = os.path.normpath(target_dir + file)
print("Copying %s to %s" % (file, dest))
shutil.copy(file, dest)
像这样称呼它:
target_dir = '/tmp/dummy'
files = [ '/tmp/dir/file1', '/tmp/dir/subdir/file2', '/tmp/file3' ]
cp_parents(target_dir, files)
输出是:
Creating /tmp/dummy/tmp/dir/subdir
Copying /tmp/dir/file1 to /tmp/dummy/tmp/dir/file1
Copying /tmp/dir/subdir/file2 to /tmp/dummy/tmp/dir/subdir/file2
Copying /tmp/file3 to /tmp/dummy/tmp/file3
可能有更好的方法来处理这个问题,但它确实有效。