我想知道 python 是否提供了一种规范的方法来将文件复制到附加了其原始前导目录的目录,就像 cp --parents 那样。来自 cp 手册页:
`--parents'
[...]
cp --parents a/b/c existing_dir
copies the file `a/b/c' to `existing_dir/a/b/c', creating any
missing intermediate directories.
我在 shutil 文档中没有看到任何相关内容。当然,我可以在将任何文件复制到 existing_dir 目录之前创建整个目录结构,但这样做可能会产生开销。
请您参考如下方法:
我终于想出了下面的代码。它的行为几乎与 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
可能有更好的方法来处理这个问题,但它确实有效。
