Python Forum

Full Version: Remove files from a directory
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello
Below is an example from a book called Automating the boring stuff with Python.
This code is supposed to deletes all files that end with .txt in a directory:
Quote:import os
for filename in os.listdir("C:\\dir"):
   if filename.endswith('.txt'):
       os.unlink(filename)


But it doesn't work.
Can someone tell what is the problem.

Thanks
How exactly doesn't work? Any error messages you can show us? Any strange behavior?

First of, you can use os.scandir(). It's faster. These two methods would list directories too. If you have a directory name matches the pattern you'll get an error when try to delete it. 

os.remove(path) is one to delete a file.
Also if you import glob module you can scan a directory for specific files.
from glob import glob

for file in glob('C:/dir/*.txt'): # a forward slash will work too in Windows
    if file:
        os.remove(file)
Edit: I did my research. os.unlink seems to works too. Didn't know it :)
It do work.
This is the path C:\\dir,
Here you suppose to give name to a folder you have,with some .txt files.
As it are now you most have a folder named dir under root C:\ to make it work.
Thanks.