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

1

7

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!

Dynode answered 20/4, 2017 at 9:25 Comment(3)
Possible duplicate of Python moving files and directories from one folder to anotherFoeticide
using shutil.move(src, dst, copy_function=copy2)Toomay
this should do the trick: docs.python.org/2/library/shutil.html#shutil.moveMaratha
P
30

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)
Poteen answered 20/4, 2017 at 10:16 Comment(1)
In the 'if' condition, replace the variable LL by L. Typo.Homogenize

© 2022 - 2024 — McMap. All rights reserved.