繁体   English   中英

如何在有条件的情况下删除txt中的几行

[英]How to delete several lines in txt with conditional

每个人! 我刚开始学习 python
我对某个 txt 文件有疑问,我想删除 KMAG 小于 5.5 的所有数据,但我不知道有什么建议? 下面的代码正是我能做到的

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

在此处输入图像描述

你需要做两件事。 首先,该文件似乎具有由单个十进制数字分隔的多行记录。 使用它一次读取文件一条记录:

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

现在您可以查看每条记录以查看是否要保留其数据。 我使用decimal模块是因为 python 二进制float并不完全代表十进制浮点数。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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