我试图在下面使用删除一些名称与条件匹配的文件,包含'aa1','bb1','cc1','dd1'。
它没有给出任何错误,但是没有一个这样的文件要删除。
for f in os.listdir(working_folder):
if 'aa1' in f or \
'bb1' in f or \
'cc1' in f or \
'dd1' in f:
try:
os.remove(os.path.join(working_folder, f))
except OSError:
print "there's no such a file"
问题1:改进代码中的多个'或'的方法是什么?
问题2:我怎样才能打印“没有aa1”,“没有bb1”等等。?
我在下面尝试过它并没有工作:
for f in os.listdir(working_folder):
for k in pattern:
if re.search(k, f):
try:
os.remove(os.path.join(working_folder, f))
except OSError:
print "there's no such a file"
squiguy建议的方式:
working_folder = 'C:\\'
pattern = ['aa1', 'bb1', 'cc1', 'dd1']
files_to_delete = []
for a in pattern:
for f in os.listdir(working_folder):
if a in f:
files_to_delete.append(f)
for b in files_to_delete:
os.remove(os.path.join(working_folder, b))
print os.path.join(working_folder, b) + " removed"
答案 0 :(得分:3)
您可以使用any
缩短该条件。
patterns = ['aa1', 'bb1', 'cc1', 'dd1']
for f in os.listdir(working_folder):
if any(pattern in f for pattern in patterns):
try:
os.remove(os.path.join(working_folder, f))
except OSError:
print "there's no such a file"