how to delete all old files ? but keeps only 3 latest files

in Python


from pathlib import Path

D = Path('/home/abanoub/Work')

files = [(i, i.stat().st_mtime) for i in D.iterdir()

    if i.is_file()]

result = sorted(files, key = lambda w: w[1])[::-1][3:]

for file, day in result:


in Bash script. find command shows randomly, so we use ls -t.


files = ($(ls -lt ~/Work))

len = ${#files[@]}

for ((i=3; i < $len; i++))


rm -f ~/Work/${files[$i]}


in Perl

perl -e'opendir$h,"/tmp";@f=sort{-M$a<=>-M$b}grep{-f}readdir$h;unlink@f[3..$#f]'

If you want to get new posts, make sure to subscribe to Value In Brief by Email.