Deleting files from folder

Question:

I have files in folder with names 1.jpg, 2.jpg, 3.jpg … etc.
And I have list of names 2.jpg, 3.jpg, 4.jpg
How can I delete files in folder according to names from this list?

import os
import glob

fileList = glob.glob(‘/home/varung/Documents/python/logs/**/*.txt’,
recursive=True)

for filePath in fileList:
try:
os.remove(filePath)
except OSError:
print("Error while deleting file")

I don’t understand why quotes don’t work.
I found this code but it only works for patterns. I can’t understand how to put names from list inside. I need to delete files in folder if their names match names from list.

Asked By: Vladimir Dnepr

||

Answers:

this code does what you’ve described:

import os

removals = ['a.txt', 'b.jpg']

for object in os.listdir('.'):
    if os.path.isfile(object) and object in removals:
        os.remove(object)
Answered By: Dariush Mazlumi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.