在我的代码中,我将整个文件夹加载到列表中,然后尝试摆脱列表中除.mp3文件之外的所有文件。
import os
import re
path = '/home/user/mp3/'
dirList = os.listdir(path)
dirList.sort()
i = 0
for names in dirList:
match = re.search(r'\.mp3', names)
if match:
i = i+1
else:
dirList.remove(names)
print dirList
print i
运行文件后,代码确实删除了列表中的某些文件,但具体保留了这两个文件:
我不知道发生了什么,为什么这两个命令专门逃避了我的搜索。
最佳答案
您正在循环内修改列表。这可能会导致问题。您应该改为遍历列表的副本(for name in dirList[:]:
),或创建一个新列表。
modifiedDirList = []
for name in dirList:
match = re.search(r'\.mp3', name)
if match:
i += 1
modifiedDirList.append(name)
print modifiedDirList
甚至更好的是,使用列表理解:
dirList = [name for name in sorted(os.listdir(path))
if re.search(r'\.mp3', name)]
没有正则表达式的同一件事:
dirList = [name for name in sorted(os.listdir(path))
if name.endswith('.mp3')]
关于python - 为什么这些字符串会从python的正则表达式中转义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4636300/