0

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?

gboffi
  • 22,939
  • 8
  • 54
  • 85

1 Answers1

0

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.

Swakeert Jain
  • 776
  • 5
  • 16
  • I got this error: files = os.path.join(path, f)) for f in os.listdir(path)) ^ SyntaxError: invalid syntax –  Nov 07 '17 at 15:13
  • Sorry I was careless with the syntax. Was focussing on the logic. files = [f for f in os.listdir(mypath) if os.isfile(os.path.join(path, f))] – Swakeert Jain Nov 07 '17 at 15:15
  • let me know if that works and I will update my answer aswell – Swakeert Jain Nov 07 '17 at 15:15
  • thank yoi for you answers, but it gives this error: OSError: [Errno 2] No such file or directory: 'file002.npy'. This file exists already. –  Nov 07 '17 at 15:25
  • Just add a path join command in the remove function. I realise that in the updated code, the path wasn't joined when inserting it into the list, just being checked – Swakeert Jain Nov 07 '17 at 15:27