Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting certain files using python

Tags:

python

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

The script processes the test.hgx and creates a new test_bac.hgx and on re-run it creates test_bac_bac.hgx. So everytime running the script creates a file with '_bac'.

Is there some solution that I can use in my script that can delete all the existing '_bac' and '_bac_bac...' files before start of the actual code.

I am already using glob.glob function

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

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

Any help/idea would be appreciated.

Thanks

like image 973
user741592 Avatar asked Jul 15 '11 07:07

user741592


People also ask

How do you delete a specific file in Python?

Using the os module in python To use the os module to delete a file, we import it, then use the remove() function provided by the module to delete the file. It takes the file path as a parameter. You can not just delete a file but also a directory using the os module.

How do you permanently delete a file in Python?

In Python, you can use the os. remove() method to remove files, and the os. rmdir() method to delete an empty folder. If you want to delete a folder with all of its files, you can use the shutil.


3 Answers

import os
import glob
for hgx in glob.glob("*_bac.hgx"):
  os.remove(hgx)
like image 151
Jacob Avatar answered Nov 14 '22 03:11

Jacob


A very similar solution would be

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

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

like image 7
mjhoffmann Avatar answered Nov 14 '22 05:11

mjhoffmann


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

like image 1
carlpett Avatar answered Nov 14 '22 04:11

carlpett