我逐行读取文件,这是我需要在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('')中采用此格式时,才会读取该文件。 但我希望它只在行以'&lt;'开头时读取该行但如果该行以任何其他字符开头,我希望它跳过,直到它遇到以'&lt;'开头的另一行。我该怎么做。谢谢
答案 0 :(得分:0)
begin = False
with open(filename, 'r') as fid:
line = fid.readline()
if line.startwith('<'):
begin = True
if begin:
do_something()