user5597655
user5597655

Reputation:

Unable to delete files of certain extension

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?

Upvotes: 1

Views: 113

Answers (2)

Fomalhaut
Fomalhaut

Reputation: 9825

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

Upvotes: 3

user5597655
user5597655

Reputation:

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.")

Upvotes: 1

Related Questions