2016-02-10 81 views
-2

林逐行讀取文件中的行,這是條件(見下文),我需要在Python實現我該怎麼做,Python程序停留在循環

如果行開頭是「<」 繼續或 跳過通過文件到行的行始於「<」 然後程序可以繼續

keyword = "TrapQueueCounter" 

count = 0 

LastLine='' 


def get_last_date(): 
    try: 
     with open('last_date.txt') as last_date_file: 
      last_date_str = last_date_file.read().strip() 
      return datetime.datetime.strptime(last_date_str, '%Y-%m-%d %H:%M:%S %f') 
    except IOError: 
     #return a date before anything in the logs 
     return datetime.datetime.strptime('1990-01-01 00:00:00 000000', '%Y-%m-%d %H:%M:%S %f') 


def set_last_date(t): 

    with open('last_date.txt', 'w') as last_date_file: 
     last_date_str = t.strftime('%Y-%m-%d %H:%M:%S %f') 
     last_date_file.write(last_date_str) 


t0 = get_last_date() 

for logpath in glob.glob('/*.log'): 
    #loop through all the files 

    print ('logpath:',logpath) 
    with open(logpath, 'r') as logfile: 
     for line in logfile: 
      line = line.strip() 
      if line.startswith('<'): //this is where iam stuck.. 
       continue 
      datepart,_,_ = line.partition('>') 
      datepart = datepart[1:] 

      date, time, ms, tz = datepart.split(' ') 

      year,month,day = date.split('.') 
      hour,minute,second = time.split(':') 

      year,month,day = int(year), int(month), int(day) 
      hour,minute,second = int(hour), int(minute), int(second) 
      ms = int(ms) 

      t = datetime.datetime(year=year, month=month, day=day 
          , hour=hour, minute=minute, second=second 
          , microsecond=ms*1000.0) 

      if t < t0: 
       continue 


      #line = line.lower() 
      count += line.count(keyword) 

      set_last_date(t) 


      if keyword in line: 
       message1 = 'Counted %s %s times in %s line' % (repr(keyword), count, line) 
       LastLine=line 
       print message1 

文件正在只讀如果線路是在起始日期格式,時間,ms, tz = datepart.split('')。 但我希望它只在行以'<'開始時纔讀取行,但如果行以其他字符開頭,我希望它跳過,直到遇到以'<'開頭的另一行。我該如何做。謝謝

+0

你可以發佈你的代碼的相關部分?這會給我們一些工作。 – Stidgeon

+0

剛剛發佈的代碼謝謝 – adus

回答

0
begin = False 
with open(filename, 'r') as fid: 
    line = fid.readline() 
    if line.startwith('<'): 
     begin = True 
    if begin: 
     do_something()