michaelmeyer michaelmeyer - 1 year ago 119
Python Question

Copy a file into a directory with its original leading directories appended

I wonder if python provides a canonical way to copy a file to a directory with its original leading directories appended, like

cp --parents
does. From
cp
man page :

`--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.


I haven't seen anything in
shutil
documentation that refers to this. Of course, I could create the whole directory structure in
existing_dir
directory before copying any file to it, but it is perhaps overhead to do this.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download