简体   繁体   中英

Deleting certain files using 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

import os
import glob
for hgx in glob.glob("*_bac.hgx"):
  os.remove(hgx)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM