Python读取文件并在满足条件时停止
我正在尝试写一个程序,这个程序会读取一个文件夹里的所有文件。当它找到'color=brown'这个内容时,程序就应该停止继续读取,即使在后面的文件中也发现了'color=brown'。我的意思是,只要第一次满足这个条件就可以了。
我之前写了一个程序,它会打印出所有文件中的'color=brown',但我希望在第一次找到后就停止。请帮帮我!
import os
path = r'C:\Python27'
data = {}
for dir_entry in os.listdir(path):
dir_entry_path = os.path.join(path, dir_entry)
if os.path.isfile(dir_entry_path):
with open(dir_entry_path, 'r') as my_file:
for line in my_file:
for part in line.split():
if "color=brown" in part:
print part
请帮帮我!非常感谢你的回答!
2 个回答
3
你可以设置一个变量来表示你已经完成了,然后从每个循环中跳出来。不过,根据循环的嵌套情况,使用异常来跳出循环可能会更简洁一些(有点像C语言中的goto语句):
try:
for m in range(10):
for n in range(10):
if m == 5 and n == 15:
raise StopIteration
except StopIteration:
print "found"
else:
print "not found"
print "always runs unless the other clauses return"
2
你在找的是“break”这个语句。
...
if "color=brown" in part:
print part
# set some variable to check at the last thing before your other for loops
# turnover.
br = True
break
然后用这个语句来跳出你启动的每两个“for”循环。
if br == True:
break
else:
pass
if br == True:
break
else:
pass