Jonathan Petts
Jonathan Petts

Reputation: 107

Trying to delete file by extension

So I am trying to delete files by extension and everything seem to be working fine - I can find the DRX files, count and display them but when I try to remove them it just doesn't seem to do anything. I'm sure I've done something really obvious wrong.

#!/usr/bin/env python3
import os
import sys
import site
import threading
import time
from os import path 
from os import listdir
from os.path import isfile, join



print ("")
file = (input("Please drag and drop the folder containing DRX files you wish to delete : "))
path = file[:-1]
os.chdir(path)
drx = [x for x in os.listdir() if x.endswith(".drx")]
amount = (str(len(drx)))

print("")
print("")
print("")
print ('I have found ' + amount + ' files with the .drx extension and these will now be deleted')
print("")
print("")
print(*drx,sep='\n')
print("")
print("")
print("")
exts = ('.drx')

for item in path:
    if item.endswith(".drx"):
        os.remove(item)

Upvotes: 0

Views: 101

Answers (2)

Rahul
Rahul

Reputation: 11520

for item in path:
    if item.endswith(".drx"):
        os.remove(item)
  1. Here your path is something like "/home/path/to/file.drx" so looping over that will give your character one by one as pointed by @FlyingTeller.
  2. you don't need if item.endswith(".drx") again. you have already done that with list comprehensiton drx = [x for x in os.listdir() if x.endswith(".drx")]. just use it.

for item in drx: os.remove(item)

  1. Your code is messy. you can do print("\n"*3) for printing 3 blank lines

Upvotes: 0

FlyingTeller
FlyingTeller

Reputation: 20462

drx is your list of files that end with drx, you can do

for item in drx:
    os.remove(item)

path is only a string (the name of the path you want to search), so looping over it will loop over the letters.

Upvotes: 3

Related Questions