lundi 4 octobre 2021

Move Files from a Directory to Another Based on a Condition

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
        }

Aucun commentaire:

Enregistrer un commentaire