如何从多个文件夹中删除特定数量的文件?

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

假设我有一组文件夹。我每个文件夹我有超过 1000 个文件,我需要在每个文件夹中计算 1000 个而不是删除其余的, 例如:

Folder1 包含 1234 个 numpy 文件,我想保留 1000 个并删除 234 个文件。

我使用python,我显示每个文件夹的文件数,但我不能只保留1000个文件并删除其余文件。

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))

你能帮帮我吗?

试试这个:

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))

我相信这应该可以解决问题。