2017-06-13 96 views
0

我收到上述错误,当我试图从我的目录列表错误:ValueError异常:list.remove(X):在列表X不同时,从目录列表

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

输出删除.z​​ip文件删除文件夹:

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

现在去除.zip文件我写了下面的代码:

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

输出:

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

我在哪里出错了?

+2

你想从目录中删除?或者变量? –

+0

从错误中不明显吗? '“* .zip”'不在你的列表中...... –

回答

2

list删除时,您不能使用通配符,你必须来遍历它,如果你想与部分匹配做掉,例如:

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

出于好奇,任何不使用'endswith'的理由? – Wondercricket

+0

我认为如果使用'.endswith()'而不是依赖切片符号,它会更健壮。 –

+0

@Wondercricket - 性能......'str.endswith()'完全一样,只是经历了几个箍。 Python版本的速度提高了10-20%,并且不像被认为是“非Pythonic”那样神秘或难以理解。 – zwer

0
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)) 
+0

看到其他答案是如何被接受的,可以假定OP没有要求从目录中删除文件 – Wondercricket

相关问题