Home > Mobile >  Python to check a word and write the rest of the line into a txt file as normal lines
Python to check a word and write the rest of the line into a txt file as normal lines

Time:08-25

I was just trying to segregate a log file into 3 different files. Each line starts with either 'INFO', 'DEBUG' or '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. 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. Also i want them to be written as plainly as in logfile.txt and not like "['Debug', 'Example']" but more like "Debug Example". Please help me out with this. I'm trying to google but nothing seems to help me with this.

CodePudding user response:

That happens because you overwrite the file's content each time since you're using w . To do what you're looking for you should use a in order to append the line each time like so:

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

CodePudding user response:

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). Append mode probably makes more sense.

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)

CodePudding user response:

Here is a much simpler way of doing things.

Not sure why you are splitting the lines, key[0] etc.

I have commented out a print stmt, you can use it to understand the solution better.

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.

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)
  • Related