3

Possible Duplicate:
Deleting files by type in Python on Windows

How can I delete all files with the extension ".txt" in a directory? I normally just do

import os
filepath = 'C:\directory\thefile.txt'
os.unlink(filepath)

Is there a command like os.unlink('C:\directory\*.txt') that would delete all .txt files? How can I do that? Thanks!

jcoppens
  • 5,306
  • 6
  • 27
  • 47
creativz
  • 10,369
  • 13
  • 38
  • 35

3 Answers3

15
#!/usr/bin/env python

import glob
import os

for i in glob.glob(u'*.txt'):
  os.unlink (i)

should do the job.

Edit: You can also do it in "one line" using map operation:

#!/usr/bin/env python

import glob
import os

map(os.unlink, glob.glob(u'*.txt'))
Aif
  • 11,015
  • 1
  • 30
  • 44
4

Use the glob module to get a list of files matching the pattern and call unlink on all of them in a loop.

Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
0

Iterate through all files in C:\directory\, check if the extension is .txt, unlink if yes.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005