简体   繁体   中英

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 :

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM