How to copy a folder into an existing folder using python

Question:

I am new to python, and am currently trying to copy a folder ‘foo’ (potentially with some files/folders inside) into another existing folder ‘bar’. After this, there should be a new path created that should look something like this "…bar/foo/*".

By copying ‘foo’ into ‘bar’ I do not wish to have the original contents in ‘bar’ to be removed, and the only changes in ‘bar’ is a new subfolder ‘foo’ being added.

I have tried to search online for the solution, but was not able to find any libraries that provide such a feature. I would highly appreciate it if I could be provided with some information on how to get started, as I am in need of this feature for another item that I am working on.

The current python version I am using is 3.8.9, so I am able to use any new libraries that were introduced from 3.0 onwards. The platform I am working on is windows.

Asked By: Ken

||

Answers:

You can use the copytree() method. Because it copy the actual content, you need to create the folder first with os.mkdir

import shutil
import os

directory = "foo"
path = os.path.join(parent_dir, directory)    
os.mkdir(path)

source_dir = r"C:foo"
destination_dir = r"C:barfoo"
shutil.copytree(source_dir, destination_dir)

Some documentation

Another solution is to use directly the command line and launching the copy/paste command from there

You can do it by importing the os import os and then with os.system(my_command) where my_command is the string containing the actual command. In linux you can use cp -r directory-1 directory-2 (to copy a directory, you need to add the -r (or -R) flag—which is shorthand for --recursive)

os.system('cp -r C:foo C:bar')
Answered By: NicoCaldo

For a general solution that can be used with source paths that change at runtime, you can use os.path.basename to peel off the directory name from the source and tack it on the destination:

import shutil
import os

full_original_directory_name = "/deeply/nested/directory/name"
target_directory = "/some/other/path"

src = full_original_directory_name
dst = os.path.join(target_directory, os.path.basename(full_original_directory_name))
shutil.copytree(src, dst)
Answered By: ddffnn