Deleting files, keeping a few -- in Python
And the same again, only as a script, just because:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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...
1 comment :
Changing fcompare to:
fcompare = lambda x,y: cmp(os.path.getmtime(x), os.path.getmtime(y))
makes it a two-liner...
Post a Comment