Search code examples
pythonfilecsvlinesidentify

Function to identify lines and writing in one file (csv)


I have a log file with a lot of lines. The log file is in csv Format. I am searching in that file for different Messages and I want to store them in a different file.

How can I manage that?

Currently I am doing it like this:

with open('/tmp/result/warnings/test/test3.csv', 'r') as input_file:
    with open('/tmp/result/warnings/test/test4.csv', 'w') as output_file:
        for line in input_file:
            if not "Failed to open output file" in line:
                output_file.write(line)

with open('/tmp/result/warnings/test/test4.csv', 'r') as input_file:
    with open('/tmp/result/warnings/test/test5.csv', 'w') as output_file:
        for line in input_file:
            if not "Invalid file length of" in line:
                output_file.write(line) 

Can I do it like looking up several Messages in once and then write in in one file?


Solution

  • with open('/tmp/result/warnings/test/test3.csv', 'r') as input_file:
        with open('/tmp/result/warnings/test/test4.csv', 'w') as output_file:
        for line in input_file:
            conditions = [not "Failed to open output file" in line, not "Invalid file length of" in line]
            if all(conditions):
                output_file.write(line)
    

    Will allow you to check against multiple conditions and if they are all true, write to the file.