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!

0

3 Answers 3

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'))
Sign up to request clarification or add additional context in comments.

1 Comment

Use u'*.txt' (note the u at the start of the string) to handle filenames containing Unicode characters.
4

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.