Home > Enterprise >  Remove multiple files match in list in Python
Remove multiple files match in list in Python

Time:07-27

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)

CodePudding user response:

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!

CodePudding user response:

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)
  • Related