How to copy contents of a directory with the same name into another directory in python

Question:

How can I copy contents of a directory with the same name into another directory?

Directory1
File1.txt

Directroy1
File2.txt

I want it to end up like

Directory1
File1.txt
File2.txt

Right now I am trying to use the shutil.move() command but it gives me an error when the directory already exists.

Here is the code for the function

def move_files(source_path, destination_path, directories):
    for dir in directories:
        shutil.move(f'{source_path}\{dir}', f'{destination_path}\{dir}')
Asked By: Brian

||

Answers:

side note : in any given path, two folders with the same name cannot exist. The name of a folder or file must be unique within its parent directory. So

  • pathDirectory1 File1.txt
  • (same)pathDirectroy1 File2.txt

Can not be existed

import shutil
import os

# Define the source and destination directories (different path fo each folder)
src_dir = "D:\code101\python\directory"
dst_dir = "D:\code101\python\directory2"

# the same path but, two different name
# src_dir = "/path/to//directory"
# dst_dir = "/path/to//directory2"


# Check if the destination directory already exists
if os.path.exists(dst_dir):
    # Remove the destination directory if it already exists
    shutil.rmtree(dst_dir)

# Copy the contents of the source directory to the destination directory
shutil.copytree(src_dir, dst_dir)

The copytree function creates a new directory in the dst_dir with the same name as the source directory and copies all the files and subdirectories from the source directory into the new directory.

Answered By: Ayb009

or, you can execute shell command:

from subprocess import call

def copy_directory(src, dst):
    cmd = 'cp -a {s} {d}'.format(s=src, d=dst)
    call([cmd, src, dst], shell=True)

copy_directory('/path/dir1/.', '/path/dir2')

-a option –> recursive option

Please note the ‘.’ at end of the src path — this indicates we are copying all files/dirs within the src dir as opposed to copying the dir2 itself into dir1

Answered By: yukako
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.