Jaff
Jaff

Reputation: 185

A function to copy folder along with its contents python

Is there a function that copies a parent folder along with all its content to a specified destination ?

I have used different functions but they seem to copy the contents excluding the parent folder.

Upvotes: 7

Views: 11324

Answers (4)

Trulli
Trulli

Reputation: 13

Simply append the source directory you want to copy in the destination:

import shutil

shutil.copytree("source", "destination/source")

If you do not have fixed strings then use os.path.basename() to determine basename and combine it in the destination with os.path.join()

import os.path
import shutil

source = "/Projekte/python/source"
shutil.copytree(source, os.path.join("destination", os.path.basename(source)))

Upvotes: 0

niek tuytel
niek tuytel

Reputation: 1179

In python 3.* we can use shutil

import shutil

old_folder = "D:/old_folder"
new_folder = "D:/new_folder"
shutil.copytree(old_folder, new_folder, dirs_exist_ok=True)

dirs_exist_ok=True is for ignoring the exception when the folder already exists in the new location.

Upvotes: 1

Andria
Andria

Reputation: 5075

import shutil
shutil.copytree(srcDir, dst, symlinks=False, ignore=None)

Upvotes: -1

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

shutil.copytree comes to mind immediately, but your issue is that copying directory foo in bar doesn't create bar/foo.

My proposal:

import shutil,os

def copytree2(source,dest):
    os.mkdir(dest)
    dest_dir = os.path.join(dest,os.path.basename(source))
    shutil.copytree(source,dest_dir)
  • first create destination
  • then generate destination dir, which is the destination added source basename
  • perform copytree with the new destination, so source folder name level appears under dest

There's no subtle check about dest directory already exist or whatnot. I'll let you add that if needed (using os.path.isdir(dest) for instance)

Note that functions from shutil come with a note which encourages users to copy and modify them to better suit their needs.

Upvotes: 11

Related Questions