简体   繁体   中英

How to delete several lines in txt with conditional

everyone! I have just started learning python
I have a problem with some txt file I want to delete all data with KMAG less than 5.5 but I have no idea any suggestions? code below just what I could

file = open("experiment.txt", "r")
for line in file:
if 'KMAG' in line:
    print(line)
file.close()

enter image description here

You need to do two things. First, it appears that this file has multiline records delimited by a line with a single decimal number. Use that to read the file a record at a time:

import re
from decimal import Decimal

def get_records(fileobj):
    record = []
    for line in fileobj:
        if re.match(r"\s*\d+\s*$", line):
            # got new record, emit old
            if record:
                yield record
            record = [line]
        else:
            record.append(line)
    if record:
        yield record
    return

Now you can peek into each record to see if its data you want to keep. I'm using the decimal module because because the python binary float does not exactly represent decimal floats.

min_val = Decimal("5.5")

with open("experiment.txt") as infile, open("foo.txt", "w") as outfile:
    for record in get_records(infile):
        # we got record number\nheader\ndata with kmag\n...
        kmag = re.split(r"\s+", record[2].strip())[-1]
        if Decimal(kmag) >= min_val:
            outfile.writelines(record)

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