Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python to copy the directory structure

Tags:

python

file

copy

Is it possible to write a script in python to do the following thing.

Basic Operation : copy files with the proper directory structure.

Given a list of file names , the program should scan the directory, and copy the files in the directory to a destination directory maintaining the folder structre. This is something like 'Export file system by creating appropriate subfolders' functionality in eclipse.

like image 521
user2434 Avatar asked Oct 28 '25 05:10

user2434


2 Answers

You can use shutil.copytree.

Update: You can take a look at the shutil.py source code to see how it is implemented.

like image 136
silviubogan Avatar answered Oct 31 '25 02:10

silviubogan


Update: I just saw that the question was to copy directory structure and files. My answer below is for directory structure only without files and python3 only as pointed out by yossi. I would still like to leave my answer as is and hope not to be downvoted.

I found the upvoted answer by silviubogan quite helpful in solving the problem (which I too, were faced with several times), so here's my approach:

shutil.copytree() accepts a copy_function so all you need is a copy function that does not copy files. Here is a slightly altered version of shutil.copy2() that does that:

def copy_dir(src, dst, *, follow_sym=True):
    if os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))
    if os.path.isdir(src):
        shutil.copyfile(src, dst, follow_symlinks=follow_sym)
        shutil.copystat(src, dst, follow_symlinks=follow_sym)
    return dst

And then a call to shutil.copytree(source, target, copy_function=copy_dir) re-creates the folder and sub-folder structure from source at target.

like image 27
Malhelo Avatar answered Oct 31 '25 04:10

Malhelo