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)
view raw gistfile1.py hosted with ❤ by GitHub

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


1 comment :

Martin J said...

Changing fcompare to:

fcompare = lambda x,y: cmp(os.path.getmtime(x), os.path.getmtime(y))

makes it a two-liner...