-1

In a folder containing , say 5 zip files say we have the following files 123_456_2018_01_01.zip 123_456_2018_01_02.zip 789_456_2018_11_02.zip 789_456_2018_11_12.zip 889_456_2018_11_02.zip

I want to remove the oldest file, i.e 123_456_2018_01_01.zip then 789_456_2018_11_02.zip

how would I accomplish this in Python ? Any help would be appreciated

Titan4
  • 11
  • 1
  • Iterate over the files in the directory and sort the file names in ascending order, then delete in whatever way you want. – BcK Apr 20 '18 at 07:41
  • Take a look at these posts: https://stackoverflow.com/a/539024/3287355 and https://stackoverflow.com/a/168435/3287355 – moonwalker7 Apr 20 '18 at 09:54

2 Answers2

0

If all files have the same pattern, you can use this:

import os
list_of_files = os.listdir() # returns list of current directory files
file_to_be_deleted = sorted(list_of_files)[0]

Now you have the name of the file that should be deleted in file_to_be_deleted, then use os.remove() to delete the file.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
-1

Store your files names in an string array, then sort it

array.sort()

and use os.remove to remove it

for i in array:
    os.remove(i)
el famoso
  • 150
  • 1
  • 8