0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.