I wonder if python provides a canonical way to copy a file to a directory with its original leading directories appended, like
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
I finally came up with the following code. It acts almost exactly as cp --parents
does.
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)
Call it like this:
target_dir = '/tmp/dummy'
files = [ '/tmp/dir/file1', '/tmp/dir/subdir/file2', '/tmp/file3' ]
cp_parents(target_dir, files)
Output is:
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
There is probably a better way to handle this, but it works.