0
import glob
import os
filelist=glob.glob("/home/test/*.txt")
for file in filelist:
  os.remove(file)

I'm able to delete all files through above code. But I don't want to delete latest 2 files out of 10 txt files.Rest of them wanted to be deleted. Can someone help me please?

Edit:

I tried index to exclude last 2 files, Got different output. Files

-rwxrwxr-x 1 test1 test 14 May 27 2015 test.txt 
-rw-r--r-- 1 test1 test 1857 Nov 9 2016 list.txt 
-rw-r--r-- 1 test1 test 140 Jun 8 22:09 check.txt 
-rw-r--r-- 1 test1 test 570 Jun 8 22:12 ert.txt 
-rw-r--r-- 1 test1 test 0 Jul 2 03:17 1.txt 
-rw-r--r-- 1 test1 test 0 Jul 2 03:17 2.txt 

My new code is:

import glob import os 
filelist=glob.glob("/home/test/*.txt") 
for file in filelist[:-2]: 
    print file 

Output

> /home/test/1.txt 
> /home/test/2.txt
> /home/test/list.txt  
> /home/test/ert.txt
Victory
  • 121
  • 1
  • 3
  • 18

2 Answers2

2

You can sort your filelist using os.stat(f).st_mtime as the sorting key:

filelist = sorted(filelist, key=lambda f: os.stat(f).st_mtime)

Afterwards you iterate over filelist, excluding the last two files:

for f in filelist[:-2]:
    os.remove(f)
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
1

If you want exclude last 2 items in glob maches just change your for loop:

import glob
import os
filelist=glob.glob("/home/test/*.txt")
for file in filelist[:-2]:
  os.remove(file)

Otherwise you can use others answer to sort files and exclude last 2 files.

Edit:

python 2 glob

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order.

Also have a look at this:

How is Pythons glob.glob ordered?

Ali Shahrivarian
  • 311
  • 2
  • 11
  • I tried,Got different output. Files -rwxrwxr-x 1 test1 test 14 May 27 2015 test.txt -rw-r--r-- 1 test1 test 1857 Nov 9 2016 list.txt -rw-r--r-- 1 test1 test 140 Jun 8 22:09 check.txt -rw-r--r-- 1 test1 test 570 Jun 8 22:12 ert.txt -rw-r--r-- 1 test1 test 0 Jul 2 03:17 1.txt -rw-r--r-- 1 test1 test 0 Jul 2 03:17 2.txt import glob import os filelist=glob.glob("/home/test/*.txt") for file in filelist[:-2]: print file /home/test/1.txt /home/test/wars.txt /home/test/Renewal_Certificate_RSA.txt /home/test/2.txt – Victory Jul 02 '18 at 08:28
  • @Victory so what is the problem? – Ali Shahrivarian Jul 02 '18 at 08:33
  • latest 2 files was included in output. I want delete all files except latest 2 files – Victory Jul 02 '18 at 08:38