Home > Mobile >  Move Files from a Directory to Another Based on a Condition
Move Files from a Directory to Another Based on a Condition

Time:10-08

I have a main directory that contains multiple folders. I wanna loop through these sub folders, check for each sub folder if it contains more than (e.g. 10 files) keep the 10 files and move the rest to a new directory, otherwise delete the subfolder.

This is how my directory looks like:

enter image description here

Each sub directory contains around 100 files, I wanna loop through these sub directories, do a check first, keep 10 files, and move the rest to a new directory.

I would presume that this can be done with the help of pathlib or os but I need a help in writing the script.

I think the code will be something like the following:

for directory in os.listdir('path'):
    for file in os.listdir(os.path.join('path', directory)):
        if(....){
          # keep 10 files and move the rest to a new directory
        } else {
          # delete the subdir
        }

CodePudding user response:

I suggest to use shutil library for moving and removing files and directories, below is an example for moving a file from a path to another path:

import shutil

original = r'original_path_where_the_file_is_currently_stored\file_name.file_extension'
target = r'target_path_where_the_file_will_be_moved\file_name.file_extension'

shutil.move(original,target)

And below is an example for removing a directory including all it's content:

import shutil
dirPath = '/path_to_the_dir/name_of_dir/'
shutil.rmtree(dirPath)

We use the two snippets above to create the final code:


import shutil
import os
new_dir_path = "path_to_the_new_dir/new_dir_name"
for directory in os.listdir('path'):
    for index, file in enumerate(file_list := os.listdir(path_dir := os.path.join('path', directory))):
        if(len(file_list) >= 10):
          # keep 10 files and move the rest to a new directory
            if(index > 9):
             shutil.move(os.path.join(path_dir,file),os.path.join(new_dir_path,file))
        else:
          # delete the subdir
          shutil.rmtree(path_dir)

  • Related