简体   繁体   English

Python检查一个字并将该行的rest写入txt文件作为正常行

[英]Python to check a word and write the rest of the line into a txt file as normal lines

I was just trying to segregate a log file into 3 different files.我只是想将一个日志文件分成 3 个不同的文件。 Each line starts with either 'INFO', 'DEBUG' or 'ERROR'.每行都以“INFO”、“DEBUG”或“ERROR”开头。 I want to read this first word in each line and then write them into separate files as Info.txt, Debug.txt, Error.txt.我想读取每一行中的第一个单词,然后将它们写入单独的文件,如 Info.txt、Debug.txt、Error.txt。 My approach was this and I'm not sure where am i going wrong.我的方法是这样的,我不确定我哪里出错了。

def Fileparse():
key = []
with open("logfile.txt", "r") as f:
    for line in f:
        key = line.split()
        if key[0] == 'INFO':
            #l = f.readline()
            ifile = open('Info.txt', 'w+')
            ifile.write(str(key))
            ifile.write('\n')
            key.clear()                
        elif key[0] == 'DEBUG':
            #l = f.readline()
            dfile = open('Debug.txt', 'w+')
            dfile.write(str(key))
            dfile.write('\n')
            key.clear()
        elif key[0] == 'ERROR':
            #l = f.readline()
            efile = open('Error.txt', 'w+')
            efile.write(str(key))
            efile.write('\n')
            key.clear()
        else:
            continue
    f.close()
if __name__=='__main__':
    Fileparse()

this is my code and the way its performing is also a bit confusing.这是我的代码,它的执行方式也有点令人困惑。

logfile.txt:

DEBUG Heloo
INFO HELLLIIIIO
INFO Hi i am perakwa
ERROR I AM error
INFO I AM AASSA
DEBUG ISADANSLK

Info.txt:
['INFO', 'I', 'AM', 'AASSA']
akwa']


Debug.txt:
['DEBUG', 'ISADANSLK']


Error.txt:
['ERROR', 'I', 'AM', 'error']

I'm not sure why only one line is being written on the output files.我不确定为什么 output 文件上只写了一行。 Also i want them to be written as plainly as in logfile.txt and not like "['Debug', 'Example']" but more like "Debug Example".此外,我希望它们像 logfile.txt 中那样简单地编写,而不是像“['Debug','Example']”,而是更像“Debug Example”。 Please help me out with this.这个你能帮我吗。 I'm trying to google but nothing seems to help me with this.我正在尝试谷歌,但似乎没有任何帮助。

That happens because you overwrite the file's content each time since you're using w+ .发生这种情况是因为自从您使用w+以来,您每次都会覆盖文件的内容。 To do what you're looking for you should use a+ in order to append the line each time like so:要执行您要查找的操作,您应该使用a+以便每次都使用 append 行,如下所示:

open('file.txt', 'a+')

This is best dealt with using a control structure of some kind - in this case a dictionary.最好使用某种控制结构来解决这个问题——在这种情况下是字典。

The open mode in the original question is w+ which doesn't make a lot of sense because a new file will be created (read/write).原始问题中的打开模式是 w+ ,这没有多大意义,因为将创建一个新文件(读/写)。 Append mode probably makes more sense. Append 模式可能更有意义。

CONTROL = {'INFO': 'Info.txt', 'DEBUG': 'Debug.txt', 'ERROR': 'Error.txt'}

def Fileparse():
    with open('logfile.txt') as f:
        for line in f:
            key, *_ = line.split()
            if (txt := CONTROL.get(key)):
                with open(txt, 'a') as out:
                    out.write(line)

Here is a much simpler way of doing things.这是一种更简单的做事方式。

Not sure why you are splitting the lines, key[0] etc.不知道为什么要拆分行,键[0]等。

I have commented out a print stmt, you can use it to understand the solution better.我已经注释掉了一个打印 stmt,您可以使用它来更好地理解解决方案。

Basically each line is a string, and in strings you can use the 'in' keyword to check if 'INFO'/'ERROR'/'DEBUG' is present in the line.基本上每一行都是一个字符串,在字符串中你可以使用'in'关键字来检查'INFO'/'ERROR'/'DEBUG'是否存在于该行中。

with open("log.txt", "r") as filename:
    for line in filename:
        # print("--<>",line)
        if "INFO" in line:
            with open("info.txt", "a") as infofile:
                infofile.write("%s\n" % line)
                
        if "DEBUG" in line:
            with open("debug.txt", "a") as debugfile:
                debugfile.write("%s\n" % line) 
                
        if "ERROR" in line:          
            with open("error.txt", "a") as errorfile:
                errorfile.write("%s\n" % line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM