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
  deleting files in program files directory RRADC 6 3,066 Aug-21-2024, 06:11 PM
Last Post: snippsat
  Filer and sort files by modification time in a directory tester_V 5 2,387 May-02-2024, 05:39 PM
Last Post: tester_V
  Loop through all files in a directory? Winfried 10 4,259 Apr-23-2024, 07:38 PM
Last Post: FortuneCoins
  uploading files from a ubuntu local directory to Minio storage container dchilambo 0 1,354 Dec-22-2023, 07:17 AM
Last Post: dchilambo
  change directory of save of python files akbarza 3 3,390 Jul-23-2023, 08:30 AM
Last Post: Gribouillis
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 7,875 Jun-27-2023, 01:17 PM
Last Post: diver999
  Monitoring a Directory for new mkv and mp4 Files lastyle 3 2,758 May-07-2023, 12:33 PM
Last Post: deanhystad
  Read directory listing of files and parse out the highest number? cubangt 5 5,209 Sep-28-2022, 10:15 PM
Last Post: Larz60+
  Remove tag several xml files mfernandes 5 6,313 Sep-20-2022, 01:42 AM
Last Post: Pedroski55
  How to save files in a separate directory Scordomaniac 3 14,643 Mar-16-2022, 10:17 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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