tags:

views:

61

answers:

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!

+3  A: 

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ý
A: 

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

KennyTM
A: 
#!/usr/bin/env python

import glob
import os

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

should do the job.

Aif
Use `u'*.txt'` (note the `u` at the start of the string) to handle filenames containing Unicode characters.
Craig McQueen
thanks I didn't know that :)
Aif