我正在制作一个快速日志解析工具:
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/