python 处理日志文件并剥离字符

标签 python

我正在制作一个快速日志解析工具:

findme = 'important '
logf = file('new.txt')
newlines = []

    for line in logf:
        if findme in line:
            line.partition("as follows: ")[2]
            newlines.append(line) 


outfile = file('out.txt', 'w')
outfile.writelines(newlines)

不知道我应该如何使用分区之类的东西来删除文本“如下:”以及每行之前的所有内容。我没有收到错误,但我尝试删除的文本仍保留在输出中。

最佳答案

另外,我对这条线有点困惑

line.partition("as follows: ")[2]

。它根本什么也不做。也许你想要

line = line.partition("as follows")[2]

?顺便说一句,最好只在 for 循环中写入每一行,而不是在末尾写入巨大的 writelines 。您当前的解决方案将使用大量内存来存储大文件,并且根本无法处理无限文件。

最终版本将如下所示:

findme = 'important '
outfile = open('out.txt', 'w')
for line in open('new.txt'):
    if findme in line:
        outfile.write(line.partition('as follows: ')[2])

关于python 处理日志文件并剥离字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4862191/

相关文章:

python - 请求.exceptions.ConnectionError : HTTPConnectionPool

python - 在使用配置文件引导优化构建 Python 时,我必须离开计算机吗?

python - 从 pypcapfile 中的 TCP header 获取 ByteArray

python - 使用 Python 从 HTML 文件中提取文本

java - jnius.JavaException : JVM exception occurred: . ..(系统找不到指定的文件)

python - 修剪 pandas 中的每列值

python - 如何将解包运算符 ("*") 与 C 风格字符串格式一起使用?

python - 查找 Pandas 移动平均线当前和之前交叉点之间的最小值

python - 读取csv文件时如何以时间升序方式获取最近一天的行?

Python:从长格式 pandas 数据帧创建嵌套列表