Python: How to move list of folders (with subfolders) to a new directory

Question:

I have a directory that literally has 3000+ folders (all with subfolders).

What I need to be able to do is to look through the directory for those files and move them to another folder. I’ve done some research and I see that shutil is used to move files, but i’m unsure how to input a list of files to look for.

For example, in the directory, I would like to take the following folders (and their subfolders) and move them to another folder called “Merge 1”

1442735516927
1442209637226
1474723762231
1442735556057
1474723762187
1474723762286
1474723762255
1474723762426
1474723762379
1474723762805
1474723762781
1474723762936
1474723762911
1474723762072
1474723762163
1474723762112
1442209642695
1474723759389
1442735566966

I’m not sure where to start with this so any help is greatly appreciated. Thanks!

Asked By: wra

||

Answers:

Combining os and shutil, following code should answer your specific question:

import shutil
import os

cur_dir = os.getcwd() # current dir path
L = ['1442735516927', '1442209637226', '1474723762231', '1442735556057',
        '1474723762187', '1474723762286', '1474723762255', '1474723762426',
        '1474723762379', '1474723762805', '1474723762781', '1474723762936',
        '1474723762911', '1474723762072', '1474723762163', '1474723762112',
       '1442209642695', '1474723759389', '1442735566966']

list_dir = os.listdir(cur_dir)
dest = os.path.join(cur_dir,'/path/leadingto/merge_1') 

for sub_dir in list_dir:
    if sub_dir in L:
        dir_to_move = os.path.join(cur_dir, sub_dir)
        shutil.move(dir_to_move, dest)
Answered By: JeromeK
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.