Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file along with directory structure/path using python? [duplicate]

First thing I have to mention here, I'm new to python.

Now I have a file located in:

a/long/long/path/to/file.py 

I want to copy to my home directory with a new folder created:

/home/myhome/new_folder 

My expected result is:

/home/myhome/new_folder/a/long/long/path/to/file.py 

Is there any existing library to do that? If no, how can I achieve that?

like image 439
Js Lim Avatar asked Oct 11 '12 15:10

Js Lim


People also ask

How do I copy a directory structure in Python?

Method 1: Using shutil. copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying. It takes an optional argument which is “ignore”.


1 Answers

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os import shutil  srcfile = 'a/long/long/path/to/file.py' dstroot = '/home/myhome/new_folder'   assert not os.path.isabs(srcfile) dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))  os.makedirs(dstdir) # create all directories, raise an error if it already exists shutil.copy(srcfile, dstdir) 
like image 118
jfs Avatar answered Oct 16 '22 05:10

jfs