Merlin
Merlin

Reputation: 25639

Delete files with python through OS shell

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

E:\test\*.txt

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

Upvotes: 18

Views: 38769

Answers (4)

Krishna Prasad S
Krishna Prasad S

Reputation: 171

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

Upvotes: 0

RedDevil
RedDevil

Reputation: 13

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)

Upvotes: 0

Jesse Anderson
Jesse Anderson

Reputation: 4603

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")]

Upvotes: 22

cwallenpoole
cwallenpoole

Reputation: 82028

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)

Upvotes: 58

Related Questions