5

What is the easiest way to copy files from multiple directories into just one directory using python? To be more clear, I have a tree that looks like this

+Home_Directory
  ++folder1
   -csv1.csv
   -csv2.csv
  ++folder2
   -csv3.csv
   -csv4.csv

and I want to put csv1,csv2,...etc all into some specified directory without the folder hierarchy.

+some_folder
   -csv1.csv
   -csv2.csv
   -csv3.csv
   -csv4.csv

Some solutions I have looked at:

Using shutil.copytree will not work because it will preserve the file structure which is not what I want.

The code I am playing with is very similar to what is posted in this question: copy multiple files in python the problem is that I do not know how to do this iteratively. Presumably it would just be another for loop on top of this but I am not familiar enough with the os and shutil libraries to know exactly what I am iterating over. Any help on this?

1

3 Answers 3

13

This is what I thought of. I am assuming you are only pulling csv files from 1 directory.

RootDir1 = r'*your directory*'
TargetFolder = r'*your target folder*'
for root, dirs, files in os.walk((os.path.normpath(RootDir1)), topdown=False):
        for name in files:
            if name.endswith('.csv'):
                print "Found"
                SourceFolder = os.path.join(root,name)
                shutil.copy2(SourceFolder, TargetFolder) #copies csv to new folder

Edit: missing a ' at the end of RootDir1. You can also use this as a starting guide to make it work as desired.

Sign up to request clarification or add additional context in comments.

2 Comments

That worked perfectly. Thank you! I really didn't have to make any tweaks except for the two directories.
Would be great if there was a .lower() function there just before .endswith() as sometimes, the extension is .PDF or sort of.
3
import glob
import shutil
#import os
dst_dir = "E:/images"
print ('Named explicitly:')
for name in glob.glob('E:/ms/*/*/*'):    
    if name.endswith(".jpg") or name.endswith(".pdf")  : 
        shutil.copy(name, dst_dir)
        print ('\t', name)

1 Comment

This code is helpful to move multiple file one directory to another directory
1

You can use it to move all subfolders from the same to a different directory to wherever you want.

import shutil
import os
path=r'* Your Path*'
arr = os.listdir(path)
for i in range(len(arr)):
  source_dir=path+'/'+arr[i]
  target_dir = r'*Target path*'
    
  file_names = os.listdir(source_dir)
    
  for file_name in file_names:
      shutil.move(os.path.join(source_dir, file_name), target_dir)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.