【发布时间】:2022-01-25 02:57:11
【问题描述】:
我正在尝试转换一个看起来像这样的日志文件
Name: AGV
Version: 1.0.00
Revision: 0000000000
Build date: 2000-00-00 00:00:00
Continuation of previous file
[1639992888.497] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 3410
[1639992888.497] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 4206
[1639992888.517] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 3433
[1639992888.517] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 4229
[1639992888.527] [B62FF420] [INFO Position.cpp:438] <AGVPOS> 602, 7787.496,
到一个 csv 文件。
我试图删除我不需要的前几行并手动为列添加名称,然后这样做,这个
df = pd.read_fwf('data.log')
df.to_csv('data.csv', index=None)
这适用于第一个日志文件,但不适用于其他文件,因为我为每个文件添加了一些额外的列。
我想要得到的输出是这样的
Timestamp. Code. Message
[1639992888.497] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 3410
[1639992888.497] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 4206
[1639992888.517] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 3433
[1639992888.517] [B62FF420] [DEBUG Wings.cpp:222] Current sidewing pressure: 4229
[1639992888.527] [B62FF420] [INFO Position.cpp:438] <AGVPOS> 602, 7787.496,
我的方法肯定不是最有效的,有没有其他方法可以做到这一点?
谢谢。
【问题讨论】:
-
在不知道您的其他日志文件的情况下,我无法确定最好的方法是什么,但我建议您不要使用
read_fwf,而是使用带有skirows 参数和分隔符'\t' 的read_csv。如果你使用 fwf 你必须确定你的分隔符的位置是什么 -
read_csv 还允许您设置列名,因此您不必担心删除第一行
-
@Carlos 所有文件看起来像这样,除了其中一些文件之间有一些看起来像这样的行
Robot started Robot charging我必须摆脱它,但其他行的格式几乎相同就像我提到的那样。 -
@Carlos 格式一般是这样的 [0000000000.000] [B62FF420] [DEBUG/INFO abcd:000] 一些消息
标签: python pandas dataframe export-to-csv