我正在从一些类似于以下文本文件中解析日期/时间/测量信息:
[Sun Jul 15 09:05:56.724 2018] *000129.32347
[Sun Jul 15 09:05:57.722 2018] *000129.32352
[Sun Jul 15 09:05:58.721 2018] *000129.32342
[Sun Jul 15 09:05:59.719 2018] *000129.32338
[Sun Jul 15 09:06:00.733 2018] *000129.32338
[Sun Jul 15 09:06:01.732 2018] *000129.32352
结果会以以下形式输出到输出文件中:
07-15-2018 09:05:56.724, 29.32347
07-15-2018 09:05:57.722, 29.32352
07-15-2018 09:05:58.721, 29.32342
07-15-2018 09:05:59.719, 29.32338
07-15-2018 09:06:00.733, 29.32338
07-15-2018 09:06:01.732, 29.32352
我使用的代码看起来像这样:
import os
import datetime
with open('dq_barorun_20180715_calibtest.log', 'r') as fh, open('output.txt' , 'w') as fh2:
for line in fh:
line = line.split()
monthalpha = line[1]
month = datetime.datetime.strptime(monthalpha, '%b').strftime('%m')
day = line[2]
time = line[3]
yearbracket = line[4]
year = yearbracket[0:4]
pressfull = line[5]
press = pressfull[5:13]
timestamp = month+"-"+day+"-"+year+" "+time
fh2.write(timestamp + ", " + press + "\n")
这段代码可以正常工作并实现了我需要的功能,但是我正在尝试学习在Python中更高效解析文件的方法。处理100MB文件需要约30秒时间,并且我有几个1-2GB大小的文件。是否有一种更快的方式来解析这个文件?
000129.32338
的结果是29.32338
?1去哪了? - Patrick Artner*0001
,读数为29.32338
,因此我不需要1。 - Jason Dunn