18

Im Tyring to Delete all Files in E:. with wildcard.

E:\test\*.txt

I would ask rather than test the os.walk. In windows.

Merlin
  • 24,552
  • 41
  • 131
  • 206

4 Answers4

58

The way you would do this is use the glob module:

import glob
import os
for fl in glob.glob("E:\\test\\*.txt"):
    #Do what you want with the file
    os.remove(fl)
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • I just ran it on my machine and it worked fine. Are you sure you have permission to remove those files? What happens if you do the following on the command promt: E:
    cd test
    del [filename]?
    – cwallenpoole Apr 03 '11 at 23:29
  • Obviously replace "[filename]" with the name of a file. – cwallenpoole Apr 03 '11 at 23:29
  • OS= windows, permission: yes "E:
    cd test
    del [filename]" on windows??
    – Merlin Apr 04 '11 at 00:34
  • 1
    Is there a reason using the glob module is the method preferred over the accepted answer? (Going by votes on answer) What advantages does it have over the other answer? – Aaron Aug 05 '16 at 13:45
  • 1
    @AaronAlphonsus It let you use the `*` instead of `if file.endswith(".txt"):` in the accepted answer. – Or Duan Jul 12 '17 at 15:48
21

A slightly verbose writing of another method

import os
dir = "E:\\test"
files = os.listdir(dir)
for file in files:
    if file.endswith(".txt"):
        os.remove(os.path.join(dir,file))

Or

import os
[os.remove(os.path.join("E:\\test",f)) for f in os.listdir("E:\\test") if f.endswith(".txt")]
Jesse Anderson
  • 4,507
  • 26
  • 36
0

You could use popen for this as well if you want to do it in fewer lines

from subprocess import Popen
proc = Popen("del E:\test\*.txt",shell=False)
RedDevil
  • 13
  • 3
  • 6
    Best to use Python libraries as it makes your code cross-platform, is less brittle and gives rich exceptions. If brevity is important, you achieve the same in one line using Python native libs with: `#import glob,os ; [os.remove(x) for x in glob.glob("E:\test\*.txt")]` – Alastair McCormack Feb 02 '16 at 21:15
0

If you want to delete file with more than one extension then define those extensions in tuple like below

import os

def purge(dir):
    files = os.listdir(dir)
    ext = ('.txt', '.xml', '.json')
    for file in files:
        if file.endswith(ext):
            print("File -> " + os.path.join(dir,file))
            os.remove(os.path.join(dir,file))
Krishna Prasad S
  • 141
  • 2
  • 17