2

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)
kali
  • 117
  • 7

2 Answers2

1

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!

Python Nerd
  • 171
  • 1
  • 9
  • 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? – kali Jul 27 '22 at 05:07
  • 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. – Python Nerd Jul 27 '22 at 05:14
  • You can also see [this link](https://stackoverflow.com/a/3207973/19629009) to understand. – Python Nerd Jul 27 '22 at 05:27
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)
OmerFaruk
  • 48
  • 5