[英]Parsing log file and writing it into csv file efficiently
我有一个使用正则表达式解析的日志文件。 它给了我3个元素
1)时间戳
2)numberid
3)对象值
我打算将此文件有效地写入CSV文件中(因为日志文件的大小可能很大)。
我已经试过了
def read_logs(input_file):
data = defaultdict()
for each in input_file:
regex_match = re(r'',each)
data['timestamp'].append(regex_match.group(1))
data['numberid'].append(regex_match.group(2))
data['objectvalue'].append(regex_match.group(3))
return data
def main(inputname,outputname):
with open(inputname) as input_file:
data = read_logs(input_file)
with open(outputname,'w') as out_file:
write_file(out_file,data)
def write_file(out_file):
out = csv.writer(out_file)
out.writerow(['timestamp_val','numberid','objectvalue'])
1)我认为使用defaultdict将是将此类数据写入文件的最有效方法。 这里的defaultdict键是timestamp
numberid
和以list为值的obejctvalue
。 如何在CSV文件中编写此代码?
样本数据值为
data = ('timestamp_val':['10:10:54','13:02:07','03:02:10'],'numberid':[AA10,BB18,FF34],'objectvalue':['NHAG','ABCD','YTAB'])
2)如果这不是一种有效的方法,那么有什么更好的方法可以做到这一点?
换句话说,我想到的是使用正则表达式读取每一行并同时在CSV文件中写入。 这是一个好方法吗?
我认为您不需要读取列表dic中的所有文件:读取后立即写入
def main(inputname,outputname):
with open(inputname) as input_file, open(outputname,'w') as out_file:
out = csv.writer(out_file)
out.writerow(['timestamp_val','numberid','objectvalue'])
for each in input_file:
regex_match = re(r'',each)
out.writerow([regex_match.group(1), regex_match.group(2), regex_match.group(3)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.