Removing specific files with python

I have a py script that processes files with the extension '.hgx'.Example: test.hgx (there are many such files with the extension hgx)

The script processes test.hgx and creates a new test_bac.hgx, and when you run it again, it creates test_bac_bac.hgx. Therefore, each time the script is run, a file with '_ bac' is created.

Is there any solution that I can use in my script that can delete all existing files '_ bac' and '_bac_bac ...' before the actual code starts.

I already use the glob.glob function

for hgx in glob.glob("*.hgx"): 

Can I use this function to delete these “X_bac.hgx” files and other _bac_bac..hgx files?

Any help / idea would be appreciated.

thanks

+7
source share
3 answers
 import os import glob for hgx in glob.glob("*_bac.hgx"): os.remove(hgx) 
+19
source

A very similar solution would be

 import os import glob map(os.remove, glob.glob("*_back.hgx")) 

But also, with a slightly more compact expression, you save one variable name in the current namespace.

+3
source

glob.glob("*_bac.hgx") will deliver the files to you. Then you can use the os.remove function to delete the file in your loop.

+1
source

All Articles