1

I want to delete multiple files which match in the items of a long list. The item in the list is like below and the list is very long:

['photo-1777.jpg', 'photo-4277.jpg', 'photo-620.jpg', 'photo-1078.jpg']

I try the following code but it fails to delete the files.

import os
path = "D://photo"
list1=['photo-1777.jpg', 'photo-4277.jpg', 'photo-620.jpg', 'photo-1078.jpg']
for x in list1:
    if os.path.exists(x):
        os.remove(x)
2
  • 2
    append the path you'll be fine. You're currently using basenames Commented Jul 27, 2022 at 4:49
  • 1
    os.remove(os.path.join(path,x)) Commented Jul 27, 2022 at 4:55

2 Answers 2

2

This is how you would do it without using os.path.exists:

from os import listdir, remove
from os.path import isfile, join

path = "D://photo/"
list1=['photo-1777.jpg', 'photo-4277.jpg', 'photo-620.jpg', 'photo-1078.jpg']

allfiles = [f for f in listdir(path) if isfile(join(path, f))]

for f in allfiles:
  if f in list1:
    try:
      remove(path+f)
    except:
      continue

Hope this helps!

Sign up to request clarification or add additional context in comments.

3 Comments

It's works! Thanks a lot. but I don't understand the usage of allfiles = [f for f in listdir(path) if isfile(join(path, f))]. Can yu explain more?
The variable path is the directory, "D://photo". listdir(path) yields all contents of the directory. The if "isfile(join(path, f))" part checks if each item is a file or directory, and only keeps the files. So if D://photo had a directory and a file, only the file would be returned.
You can also see this link to understand.
1

When specifying file paths:

  1. If the Python script and the files to be deleted are not in the same folder, you must specify the full path.
  2. You should use os.path.join when dealing with file paths.

In this case, the problem will disappear if you edit your code like this:

import os
path = "D://photo"
list1=['photo-1777.jpg', 'photo-4277.jpg', 'photo-620.jpg', 'photo-1078.jpg']
for x in list1:
    file_path = os.path.join(path, x)
    if os.path.exists(file_path):
        os.remove(file_path)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.