Skip to content Skip to sidebar Skip to footer

Python To Extract Data From A File When Particular String Is Found

I am trying to extract (LOG_LEVEL_DEBUG, CAPTIVE_RECVD_SIGCHLD) from the PUT_LOG tag whenever PUT_LOG tag is found i just want to extract information within that and put it into th

Solution 1:

With an input-file file_in, and output-file file_out and a list strings_to_filter of strings to extract from the source-file given as arguments, extract_lines(file_in, file_out, strings_to_filter) will find, for any line in file_in, whatever the brackets of PUT_LOG(...); contain in-between, cross-checks it against the list strings_to_filter of accepted strings and appends it (into a new line) to out.txt:

import os
import re


def extract_lines(file_in, file_out, strings_to_filter):
    with open(file_in) as f_in, open(file_out, "a+") as f_out:
        for line in f_in:
            res = re.search("(PUT_LOG\()(.*)(\)\;)", line)
            if res is not None:
                i = 0
                for segment in res.group(2).split(","):
                    segment = segment.strip()
                    if segment in strings_to_filter and i < 2:
                        print(segment, file=f_out)
                        i += 1

extract_lines(
                  os.path.realpath("path/to/log_file.txt"),
                  os.path.realpath("path/to/output_file.txt"),
              [
               "CAPTIVE_EXECUTE_CMD",
               "CAPTIVE_EXECUTE_CMD_FAILED",
               "CAPTIVE_RECVD_SIGCHLD",
               "LOG_LEVEL_DEBUG",
               "LOG_LEVEL_DEBUG_ERR"
               ]
              )

Post a Comment for "Python To Extract Data From A File When Particular String Is Found"