0

I am extracting data into csv and xlsxI need to delete those files simultaneously

My code :

Csv_files=glob.glob(os.path.join("*.csv))
xl_files=glob.glob(os.path.join("*.xlsx))
for f in csv_files:
 os.remove(f)
for f in xl_files:
 os.remove(f)

Instead of removing seperately,i need to delete in 3/5 line of code

Sparrow
  • 15
  • 6
  • What do you mean by simultaneously, and why is it important? See [ask] and how to create a [mcve]. – Peter Wood Apr 18 '22 at 11:44
  • [python-glob-multiple-filetypes](https://stackoverflow.com/questions/4568580/python-glob-multiple-filetypes) – kaksi Apr 18 '22 at 11:57

2 Answers2

2
from glob import glob
import os
for f in glob('*.csv') + glob('*.xlsx'):
    os.remove(f)
kaksi
  • 88
  • 6
0

itertools has lots of utility methods for this sort of problems

import itertools
Csv_files=glob.glob(os.path.join("*.csv"))
xl_files=glob.glob(os.path.join("*.xlsx"))

for f in itertools.chain(csv_files, xl_files):
    os.remove(f)
  • In what way is this simultaneous? In what way is this not separately? – Peter Wood Apr 18 '22 at 11:45
  • No need for `chain` - `glob` returns lists so you can just concatenate them – Stuart Apr 18 '22 at 11:48
  • @PeterWood i have mentioned format type twice in seperate variables and deleting the files(2 loops)..Instead of that i just want to loop though files in directory and remove format types(In single loop it should remove directory). – Sparrow Apr 18 '22 at 12:01
  • @Stuart Sorry i didnt understand.New to python – Sparrow Apr 18 '22 at 12:01