kali
kali

Reputation: 107

Remove multiple files match in list in Python

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)

Upvotes: 1

Views: 774

Answers (2)

OmerFaruk
OmerFaruk

Reputation: 48

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)

Upvotes: 1

Python Nerd
Python Nerd

Reputation: 349

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!

Upvotes: 2

Related Questions