Reputation: 563
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
Upvotes: 0
Views: 511
Reputation: 82899
You can put the else
after the for
loop:
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, i.e. if it was not exited via break
.
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
.
Upvotes: 1