Using Python to copy the directory structure
Solution 1
You can use shutil.copytree.
Update: You can take a look at the shutil.py source code to see how it is implemented.
Solution 2
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
.
user2434
Updated on June 04, 2022Comments
-
user2434 almost 2 years
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.