0

假设我有一组文件夹。我每个文件夹有超过 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))

请问你能帮帮我吗?

4

1 回答 1

0

尝试这个:

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

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

于 2017-11-07T14:44:01.883 回答