2014-12-03 32 views
0

有沒有辦法打印「no date」一次?其他語句在python中打印一次

我總是打印這樣

no date 
no date 
24 - 8 - 1995 
no date 
no date 
no date 
no date 
no date 
03 - 12 - 2014 
no date 
.... 

我想打印這樣

24 - 08 - 1995 
03 - 12 - 2014 
no date 
15 - 10 - 1995 
no date 

這是代碼

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" 

感謝幫助

回答

0

你可以把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" 

這樣,如果循環,如果它不是經由break退出正常執行,即else部分將被執行。你

可能還需要使用with所以文件被正確關閉,遍歷文件對象,而不是直接不必要加載其全部內容到內存readlines,並使用in,而不是find

+0

Thankyouu。最後這是答案 – lalalala 2014-12-03 14:34:14