-2

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.

  • your question is ambiguous. do you want to delete files which their name is included in a list, or is close to an item and/or matches a pattern? also, do you want to scan subdirectories as well, or the root directory alone? – Dariush Mazlumi Oct 24 '22 at 18:57
  • Please include some code to let us know what you've tried. – L8R Oct 24 '22 at 19:03
  • 1
    Does this answer your question? [How do I delete a file or folder in Python?](https://stackoverflow.com/questions/6996603/how-do-i-delete-a-file-or-folder-in-python) – Pranav Hosangadi Oct 24 '22 at 19:03
  • [edit] your question to add code. It is unreadable as a comment – Pranav Hosangadi Oct 24 '22 at 19:04
  • Please [edit] your question and add code and clarification there, then delete the comments. – hc_dev Oct 24 '22 at 19:05

1 Answers1

0

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)
Dariush Mazlumi
  • 186
  • 1
  • 3
  • 11