Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy directory contents into a directory with python [duplicate]

I have a directory /a/b/c that has files and subdirectories. I need to copy the /a/b/c/* in the /x/y/z directory. What python methods can I use?

I tried shutil.copytree("a/b/c", "/x/y/z"), but python tries to create /x/y/z and raises an error "Directory exists".

like image 566
prosseek Avatar asked Feb 22 '13 22:02

prosseek


People also ask

How do I copy multiple files from one directory to another in Python?

For copying multiple files at once, you'll have to have a list of all files you want to copy and loop over them to copy them. Calling shutil. copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.)

How do I copy all contents from one directory to another?

To copy multiple files with the “cp” command, navigate the terminal to the directory where files are saved and then run the “cp” command with the file names you want to copy and the destination path.


2 Answers

I found this code working which is part of the standard library:

from distutils.dir_util import copy_tree  # copy subdirectory example from_directory = "/a/b/c" to_directory = "/x/y/z"  copy_tree(from_directory, to_directory) 

Reference:

  • Python 2: https://docs.python.org/2/distutils/apiref.html#distutils.dir_util.copy_tree
  • Python 3: https://docs.python.org/3/distutils/apiref.html#distutils.dir_util.copy_tree
like image 151
prosseek Avatar answered Oct 02 '22 13:10

prosseek


You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths

glob2 link: https://code.activestate.com/pypm/glob2/

like image 30
ikudyk Avatar answered Oct 02 '22 13:10

ikudyk