我们在日志文件中具有以下数据,我们需要将其转换并放入一个csv文件中, 行应以'********************************************分隔*******************', 我们可以在python中做到这一点吗?
{
"allresponses":false
}
预期输出是csv文件,如下面的屏幕截图所示。
答案 0 :(得分:1)
示例代码:
import csv
import itertools as it
with open("input.txt") as f:
list_=[]
for key, group in it.groupby(f, lambda line: line.startswith('******')):
if not key:
d = {}
for item in list(group):
key1,value1 = item.split(":",1)
d[key1] = value1.strip("\n")
list_.append(d)
print(list_)
keys1 = list_[0].keys()
with open('output.csv', 'w') as output_file:
dict_writer = csv.DictWriter(output_file, keys1)
dict_writer.writeheader()
dict_writer.writerows(list_)
答案 1 :(得分:-1)
您可以通过以下方式来执行此操作:读取日志文件,删除不必要的字符串,然后将所需的字符串写入csv文件!
import csv
with open("data.log","r") as file:
out=file.readlines()
for i in out:
if i == '***************************************************************\n':
pass
else:
with open("out.csv","a+") as csv_file:
print(i)
writer = csv.writer(csv_file)
writer.writerow([i])
您可以在csv.writer中播放以获得所需的格式!您可以从这里开始!尝试阅读有关python csv
模块的信息!