Unable to delete files of certain extension

115 views Asked by At

I'm trying to delete some archives in a folder.

Here is what I've written to do that:

import sys
import os
from os import listdir
from os.path import join

dir_path = os.path.dirname(os.path.realpath(__file__))

for file in dir_path:
    if (file.endswith(".gz")) or (file.endswith(".bz2")):
        os.remove(join((dir_path), file))
        print("Removed file.")

print("Done.")

When I run the module, it just prints "Done." but deletes no files, even though there are files with that extension in the same directory as the module.

Can't figure out what I'm doing wrong, help?

2

There are 2 answers

0
Fomalhaut On BEST ANSWER

It looks like you missed os.listdir(dir_path) in the for-loop.

1
AudioBubble On

This seems to have worked:

import sys
import os
from os import listdir
from os.path import join

dirdir = "/Users/kosay.jabre/Desktop/Programming/Password List"
dir_path = os.listdir(dirdir)

for file in dir_path:
    if (file.endswith(".gz")) or (file.endswith(".bz2")):
        os.remove(file)

print("Done.")