Skip to content
Advertisement

Deleting the useless output files using Python

After I execute a python script from a particular directory, I get many output files but apart from 5-6 files I want to delete the rest from that directory. What I have done is, I have taken those 5-6 useful files inside a list and deleted all the other files which are not there in that list. Below is my code:

list1=['prog_1.py', 'prog_2.py', 'prog_3.py'] #Extend
import os
 
dir = '/home/dev/codes' #Change accordingly
for f in os.listdir(dir):
  if f not in list1:
    os.remove(os.path.join(dir, f))

Now here I just want to add one more thing, if the output files start with output_of_final, then I don’t want them to be deleted. How can I do it? Should I use regex?

Advertisement

Answer

You could use Regex, but that’s overkill here. Just use the str.startswith method.

Also, it’s bad practice to use reserved keywords, built-in types and functions as variable names. I have renamed dir to directory. (https://docs.python.org/3/library/functions.html#dir)

list1 = ['prog_1.py', 'prog_2.py', 'prog_3.py'] # Extend
import os
 
directory = '/home/dev/codes' # Change accordingly
for f in os.listdir(directory):
  if f not in list1 and not f.startswith('output_of_final'):
    os.remove(os.path.join(directory, f))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement