vandu
vandu

Reputation: 25

Copy all files and subfolders having .csv extension into another new path with same folder hierarchy

Let's say I have various folders(abc,bcd,cde) in my source path(C:\) with different .csv files

C:\abc\test1.csv
C:\bcd\test2.json
C:\cde\test3.csv

Need to move folders with .csv to target path(D:\) as follows:

D:\abc\test1.csv
D:\cde\test3.csv

If no folder name(abc,cde) exists in target path, then it needs to be created.

Upvotes: 1

Views: 901

Answers (1)

michaelgbj
michaelgbj

Reputation: 294

The best is to define a recursive function that copies the directory level-by-level

import os
import shutil

def selective_copy(source_dir, target_dir, file_extension):
   if not os.path.exists(target_dir):
      os.makedirs(target_dir)

   for item in os.listdir(source_dir):
      source_fn = os.path.join(source_dir, item)
      if os.path.isdir(source_fn):
         selective_copy(source_fn, os.path.join(target_dir, item), file_extension)
      elif item.endswith(file_extension):
         shutil.copyfile(source_fn, os.path.join(target_dir, item))

If you want the directory structure to only be replicated if there are files to be copied from it, You can move the "if not os.path.exists(target_dir)" conditional to right before the "shutil.copyfile(...)"

Upvotes: 1

Related Questions