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

隐身守侯 提交于 2019-12-11 14:40:54

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/47160502/how-to-delete-a-specific-number-of-files-from-many-folders

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!