简体   繁体   中英

Parsing a text file based on regex / free text

I'm new to python so trying to find a good solution / approach on how to perform some operations on a text file:

Things I want to achieve:
Go through a text file which is of 5k-10k lines find for a particular text based on regex and based some free text, by checking line by line, save it and store it to another file.

What would be the good way to achieve this in python?

Normal way of reading the files and parsing it should work?

with open("in.txt") as f:
    lines = [l for l in lines if "ROW" in l]
with open("out.txt", "w") as f1:
    f1.writelines(lines)

another way

with open("in.txt") as f, open("out.txt", "w") as f1:
    for line in f:
        if "ROW" in line:
            f1.write(line) 

Yet another approach atop @Ayoub Benayache's using re but for regex patterns if needed.

import re

pattern = re.compile(r"^.*pattern.*$", re.M|re.I)

with open("in.txt", 'r') as infile:
    lines = pattern.findall(infile.read())
with open("out.txt", 'w') as outfile:
    outfile.write('\n'.join(lines))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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