我正在关注此主题的回复:Python: parsing structured text to CSV format我在导出数据时遇到困难。我对原始主题中最佳投票结果提出的脚本做了一些修改,但我只能将最后一组结果放到CSV文件中,没有其他内容写入。
原文是:
def read_records(iterable):
record = {}
for line in iterable:
if line.isalnum():
# Nuevo registro, mantiene anterior
if record:
yield record
record = {}
continue
key, value = line.strip().split(":",1)
record[key.strip()] = value.strip()
# Archivo listo
if record:
yield record
# Salida encabezados
headers = ("Device ID", "SysName", "Entry address(es)", "IPv4 address", "Platform", "Interface", "Port ID (outgoing port)", "Holdtime")
with open("inputFile.txt") as infile, open("outputFile.csv", 'wb') as outfile:
records = read_records(infile)
writer = csv.DictWriter(outfile, headers, delimiter=';')
writer.writeheader()
# and write
writer.writerows(records)
带有少量mod的代码是:
<script src="assets/js/bootstrap.min.js"></script>
我真的被卡住了,我不知道为什么脚本只会写最后一组数据。拜托,请有人帮帮我吗?
提前致谢。
答案 0 :(得分:0)
用于分隔记录的条件不太正确,请尝试:
def read_records(iterable):
record = {}
for line in iterable:
if line.startswith('Device'):
if record:
yield record
record = {}
key, value = line.strip().split(":",1)
record[key.strip()] = value.strip()
if record:
yield record