Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

trying to split a file by specifec word in python

i have a log file and i need to save the file with the lines that has a specific words.
‘begin’ and ‘end’
for example
this is the log:

19-3-2020 05:23:20.481  INFO    12  183 creating socket for traffic CONTROL module
19-3-2020 05:23:20.481  INFO    18  189 transaction 17336 begin
19-3-2020 05:23:20.622  INFO    17  194 creating mailslot for RSVP
19-3-2020 05:23:20.622  INFO    16  187 end transaction 17336
19-3-2020 05:23:20.622  INFO    13  193 transaction 17339 begin

this is what i need:

19-3-2020 05:23:20.481  INFO    18  189 transaction 17336 begin
19-3-2020 05:23:20.622  INFO    16  187 end transaction 17336
19-3-2020 05:23:20.622  INFO    13  193 transaction 17339 begin
19-3-2020 05:23:20.792  INFO    15  194 end transaction 17339

this is the what i write:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open("exam.log", "r") as f:
    text = f.readlines()
END = 'end'
BEGIN = 'begin'
for val in text:
    if END in val:
        print(val)
    if BEGIN in val:
        print(val)

it give me what i want but i dont know what next. how to save it.

>Solution :

Write the lines to out.log instead of printing.

with open("exam.log", "r") as f:
    text = f.readlines()
END = 'end'
BEGIN = 'begin'

with open("out.log", "w") as f:
    for val in text:
        if END in val or BEGIN in val:
            f.writelines(val)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading