0

I am trying to delete all xlsx files from a folder, note it has files of other extension. Given below is what I have tried:

path = '/users/user/folder'.  <-- Folder that has all the files
list_ = []
for file_ in path:
    fileList = glob.glob(path + "/*.xlsx")
    fileList1 = " ".join(str(x) for x in fileList)
        try:
            os.remove(fileList1)
        except Exception as e:
            print(e)

But the above does not delete the xlsx files.

scott martin
  • 1,253
  • 1
  • 14
  • 36

4 Answers4

5

Try:

import os
import glob

path = '/users/user/folder'
for f in glob.iglob(path+'/**/*.xlsx', recursive=True):
    os.remove(f)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
2

you can use this code to delete the xlsx or xls file import os

 path = r'your path '
 os.chdir(path)
 for file in os.listdir(path):
     if file.endswith('.xlsx') or file.endswith('.xls'):
         print(file)
         os.remove(file)
shubham
  • 503
  • 2
  • 14
1

You can use the below code as well to remove multiple .xlsx files in a folder.

import glob, os
path =r"folder path"
filenames = glob.glob(path + "/*.xlsx")
for i in filenames:
    os.remove(i)
0

It would be better to use os.listdir() and fnmatch. Try the below code .

`import os, fnmatch

 listOfFiles = os.listdir('/users/user/folder') #filepath 
 pattern = "*.xslx"  
 for entry in listOfFiles:  
     if fnmatch.fnmatch(entry, pattern):
        print ("deleting"+entry)
        os.remove(entry)`
Path- Or
  • 43
  • 1
  • 4
  • 13