python - 将字典(或当前输出文本文件)导出到 .csv 文件而不是 .txt 文件的最简单方法?
问题描述
我为日志文件创建了一个解析器和提取器,并希望看到一个快速方法的示例:
将当前输出写入 .txt 文件并将其转换为新的 .csv 文件(可能带有
pandas
),或使用 .csv 模块将写入方法序列更改为 a
csv.writer
,然后使用csv.DictReader
.
就实用性和资源消耗而言,什么是最有效的?我当前导出的.txt
文件和相关代码发布在下面。
导出数据:
Request ID : bf710010
Username : kadaniel
ECID : 6ca4862b-14d1-4a7f-8158-5e6cac363144-001477ac
Start Time : 2019-06-12T09:14:54.947
End Time : 2019-06-12T09:14:55.22
Request ID : bf710020
Username : kadaniel
ECID : 6ca4862b-14d1-4a7f-8158-5e6cac363144-001477ac
Start Time : 2019-06-12T09:14:55.343
End Time : 2019-06-12T09:14:55.514
代码:
process_records = {}
with open(log_file_path, "r") as file:
for line in file:
m = pattern.match(line)
if m is not None: # If there is a match with pattern
(timestamp, ecid, requestid, username) = m.groups()
if requestid not in process_records:
process_records[requestid] = (timestamp, username, ecid, None)
else:
process_records[requestid] = process_records[requestid][:3] + (timestamp,)
for requestid, (start, username, ecid, end) in process_records.items():
print("Request ID: {}\nUsername: {}\nECID: {}\nStart Time: {}\nEnd Time: {}\n\n".format(
requestid,
username,
ecid,
start,
end,
))
file.close()
with open(export_file, 'w+') as file:
file.write("EXPORTED DATA:\n\n")
if pattern != None:
for requestid, (start, username, ecid, end) in process_records.items():
file.write(("Request ID : {}\nUsername : {}\nECID : {}\nStart Time : {}\nEnd Time : {}\n\n".format(
requestid,
username,
ecid,
start,
end,
)))
file.close()
我目前在字典中有数据,process_records
. 每个键 ( requestid
) 与元组中的 4 个元素相关联。我希望键和之后的每个元素代表它自己的列。
解决方案
在我看来,理想的方法是使用内置的csv库。
首先,导入库。
import csv
然后使用以下代码段进行编写 -
with open(export_file, 'w+') as file_handler:
csv_writer = csv.writer(fileobj=file_handler, delimiter=',')
for requestid, (start, username, ecid, end) in process_records.items():
csv_writer.writerow([requestid, username, ecid, start, end,])
推荐阅读
- php - 多个 vhost 可以使用同一个 php-fpm 池吗
- azure-devops - Azure Function App 结果并不总是显示在 Monitor 中
- javascript - 按属性值(数字键)对 JavaScript 对象进行排序
- javascript - 单击滑块按钮后,js滑块调用堆栈加倍
- c# - 将可空引用类型转换为不可空引用类型,不那么冗长
- java - 在选择正确的方式来捕捉相机输入时需要指针
- reactjs - 使用 nextjs 自定义路由?
- python-3.x - 如何使用 Keras 教 CNN 识别比教学数据集更大的图像上的对象
- python - 如何在 Protobuf 中序列化嵌套消息中的默认值
- java - 除了 onMapReady 之外,如何在 Google 地图中添加自定义标记