Python Forum
Remove files from a directory
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Remove files from a directory
#1
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
Reply
#2
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 :)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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.
Reply
#4
Thanks.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through all files in a directory? Winfried 9 228 10 hours ago
Last Post: DeaD_EyE
  uploading files from a ubuntu local directory to Minio storage container dchilambo 0 456 Dec-22-2023, 07:17 AM
Last Post: dchilambo
  change directory of save of python files akbarza 3 881 Jul-23-2023, 08:30 AM
Last Post: Gribouillis
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 3,341 Jun-27-2023, 01:17 PM
Last Post: diver999
  Monitoring a Directory for new mkv and mp4 Files lastyle 3 1,635 May-07-2023, 12:33 PM
Last Post: deanhystad
  Read directory listing of files and parse out the highest number? cubangt 5 2,349 Sep-28-2022, 10:15 PM
Last Post: Larz60+
  Remove tag several xml files mfernandes 5 3,819 Sep-20-2022, 01:42 AM
Last Post: Pedroski55
  How to save files in a separate directory Scordomaniac 3 1,878 Mar-16-2022, 10:17 AM
Last Post: Gribouillis
  Rename Multiple files in directory to remove special characters nyawadasi 9 6,381 Feb-16-2021, 09:49 PM
Last Post: BashBedlam
  List of error codes to find (and count) in all files in a directory tester_V 8 3,684 Dec-11-2020, 07:07 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020