scott martin
scott martin

Reputation: 1293

Python - Delete xlsx files from a folder

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.

Upvotes: 0

Views: 6622

Answers (4)

Sanjay Kumar
Sanjay Kumar

Reputation: 11

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)

Upvotes: 1

Path- Or
Path- Or

Reputation: 43

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)`

Upvotes: 0

shubham
shubham

Reputation: 513

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)

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Try:

import os
import glob

path = '/users/user/folder'
for f in glob.iglob(path+'/**/*.xlsx', recursive=True):
    os.remove(f)

Upvotes: 5

Related Questions