Search code examples
pythonpython-os

How to delete a specific number of files from many folders?


Let's suppose that I have a set of folders. I each folder I have more than 1000 files, I need to count 1000 in each folder than delete the rest, For example:

Folder1 contains 1234 numpy files, I want to keep 1000 and delete the 234 files.

I use python, I display number of files per folder, but I can't keep only 1000 files and delete the rest.

import os
b=0
for b in range(256):
    path='path.../traces_classes_Byte_0/Class_Byte_Hypothesis_'+str(b)
    num_files = sum(os.path.isfile(os.path.join(path, f)) for f in os.listdir(path))
    print('Number of files in Class_Byte_Hypothesis_'+str(b)+' is ' +str(num_files))

Could you help me please?


Solution

  • Try this:

    import os
    for b in range(256):
        files = []
        path='path.../traces_classes_Byte_0/Class_Byte_Hypothesis_'+str(b)
        files = [f for f in os.listdir(path) if os.isfile(os.path.join(path, f))]
        if len(files) > 1000:
            for f in files[1000:]:
                os.remove(os.path.join(path, f))
    

    I believe this should do the trick.