Wednesday, December 14, 2011

Deleting files, keeping a few -- in Python

And the same again, only as a script, just because:

import glob
import os
  
def fcompare(f1, f2):
  t1 = os.path.getmtime(f1)
  t2 = os.path.getmtime(f2)
  if t1 < t2:
    return -1
  if t1 > t2:
    return 1
  return 0

# TODO: parametrise the pattern and the number to retain
for f in sorted(glob.iglob('*.log'), cmp = fcompare, reverse = True)[3:]:
  os.remove(f)

If there wasn't that comparison function to write, it'd be terser...


0 comments: