Nupur Kulkarni
Nupur Kulkarni

Reputation: 63

Error: ValueError: list.remove(x): x not in list while removing folders from dir list

I am getting above error when I am trying to remove .zip files from my directory list

>>> from os import listdir
>>> from os.path import isfile,join
>>> dr = listdir(r"C:\Users\lenovo\Desktop\ronit")
>>> dr

output:

['7101', '7101.zip', '7102', '7102.zip', '7103', '7103.zip']

Now for removing .zip files I wrote following code:

>>> dr.remove("*.zip")

output:

Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
dr.remove("*.zip")
ValueError: list.remove(x): x not in list

where am I going wrong?

Upvotes: 0

Views: 589

Answers (2)

Roi S.
Roi S.

Reputation: 56

import os
from os import listdir
from os.path import join

dir = 'C:\\Users\\lenovo\\Desktop\\ronit'
dr=os.listdir(dir)

for f in dr:
    if item.endswith(".zip"):
        os.remove(join(dir, f))

Upvotes: 0

zwer
zwer

Reputation: 25829

You cannot use wildcards when removing from a list, you have to iterate through it if you want to do away with partial matches, e.g.:

filtered_list = [file_name for file_name in dr if file_name[-4:] != ".zip"]
# ['7101', '7102', '7103']

Upvotes: 2

Related Questions