[英]Else statement to print once in python
Is there a way to print "no date" once? 有没有办法一次打印“无日期”?
I always print like this 我总是这样打印
no date
no date
24 - 8 - 1995
no date
no date
no date
no date
no date
03 - 12 - 2014
no date
....
i want print like this 我想要这样打印
24 - 08 - 1995
03 - 12 - 2014
no date
15 - 10 - 1995
no date
this is the code 这是代码
import os
for dirname, dirnames, filenames in os.walk('D:/Workspace'):
for filename in filenames:
if filename.endswith('.c'):
for line in open(os.path.join(dirname, filename), "r").readlines():
if line.find('date') != -1:
print line
break
else:
print "no date"
thanks for helping 谢谢你的帮助
You can put the else
after the for
loop : 您可以将else
放在for
循环之后 :
with open(os.path.join(dirname, filename), "r") as f:
for line in f:
if 'date' in line:
print line
break
else:
print "no date"
This way, the else
part will execute if the loop executed normally, ie if it was not exited via break
. 这样,如果循环正常执行,即如果未通过break
退出,则else
部分将执行。
Also you might want to use with
so the files are closed properly, and iterate the file object directly instead of needlessly loading its entire content into memory with readlines
, and use in
instead of find
. 另外,您可能还想使用with
以便正确关闭文件,并直接迭代文件对象,而不是通过readlines
不必要地将其整个内容加载到内存中,然后使用in
代替find
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.