使用regex从文件中删除日期/时间戳重新编译以及回复sub

2024-10-04 09:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我是新来的,正在学习Python,所以谢谢你回答我的问题。我正在尝试将一个文件与另一个应该具有相同内容(时间戳除外)的文件进行比较。我试图用regex和回复sub,但我明显漏掉了什么。我也做过研究,但还没能找到我想要的工作方式。最后,我想删除日期和时间戳,但我想尝试让日期部分先工作。以下是日志文件的外观:

15/03/2019  18:25:35 0446: Successful Compile (Script file: C:\PodTools\Automation\TL000635 - Serial Interface Tool Gen2_Automation Script\Script_Pair.txt)
15/03/2019  18:25:35 0448: Pairing with the Pod
15/03/2019  18:25:35 0448: V 82 2952790016 10051
15/03/2019  18:25:35 0550: I  52 B0 00 00 00 00 00 27 43
15/03/2019  18:25:40 0974: O  3D 02
15/03/2019  18:25:40 0976: SCRIPT COMPLETE

问题代码:

import re
import datetime

today = datetime.date.today()

with open('C:\\PodTools\\Automation\\TL000635 - Serial Interface Tool Gen2_Automation Script\\OutputFolder\\'+str(today)+'\\Output_'+str(today)+'.txt') as f:
    outputFile_contents = f.readlines()

newOutputFileContents = []

pat = re.compile(r'\d{2}[-/]\d{2}[-/]\d{4}')

for line in outputFile_contents:
    [re.sub(pat, '', line)]
    newOutputFileContents.append(line)
    print(newOutputFileContents)

Tags: 文件retxttodayline时间serialscript
2条回答

要回答您的具体问题,即您的问题中包含的代码中的问题是什么,让我们看一行

[re.sub(pat, '', line)]

我怀疑这就是问题所在,因为下面几行假设line的值已经更改了—但是上面的代码没有这样做。您应该使用例如:

line = re.sub(pat, '', line)

但是,如果日志文件的每一行都有相同的格式,我建议@blhsing的答案作为剥离时间戳问题的简单解决方案。你知道吗

出于您的目的,将每行拆分为3列并只将第三列写入新文件要容易得多:

with open('file.txt') as f:
    for line in f:
        print(line.split(maxsplit=2)[2], end='')

相关问题 更多 >