Quazi Farhan
Quazi Farhan

Reputation: 1425

How to copy all files from a folder (including sub-folder) while not copying the folder structure in python

Can someone help me about how to copy all files from a folder to another destination folder in python. The catch is I do not want to copy the sub-directory structure. But I want the files within them.

For example, lets say in the root folder, there are 3 folders, each containing 10 files. Also in each of them there are 2 folders each containing 5 files. (so each first level folder has in total 20 files and 2 sub directories under it). Bringing the total to 60 files.

I wish to copy all of those 60 files to a single destination directory, discarding the subfolder structure.

This is the code I've tried:

# path : source folder path
# compiled_path: destination folder path
w = os.walk(path)
for root, dirs, files in w:
    for dir_name in dirs:
        file_list_curent_dir = os.walk(path+"\\"+dir_name).next()[2]
        for item in file_list_curent_dir:
            shutil.copy(path+"\\"+dir_name+"\\"+item, compiled_path+"\\"+item )

It copies the files uppermost level, not the folders within sub-directories.

Thank you very much for your time.

Upvotes: 18

Views: 28858

Answers (2)

Mbjahnoon
Mbjahnoon

Reputation: 31

you can use this raw function (but the best way to go when you want to go recursively over directories is os.walk)

from shutil import copyfile
import shutil
def your_function(dir):
    for folder in os.listdir(dir):
        folder_full_path = os.path.join(dir,folder)
        move_down_and_delete(folder_full_path,folder_full_path)

def move_down_and_delete(input,copy_to_dir):
    if os.path.isfile(input):
        dest = os.path.join(copy_to_dir,os.path.basename(input))
        print dest,input
        copyfile(input,dest)
        return
    for child in os.listdir(input):
         current_obj_path = os.path.join(input, child)
         move_down_and_delete(current_obj_path,copy_to_dir)
         if not os.path.isfile(current_obj_path):shutil.rmtree(current_obj_path)

Upvotes: 0

J'e
J'e

Reputation: 3716

import os
import shutil

for root, dirs, files in os.walk('.'):  # replace the . with your starting directory
   for file in files:
      path_file = os.path.join(root,file)
      shutil.copy2(path_file,'destination_directory') # change you destination dir

Upvotes: 32

Related Questions