如何在文本文件的行中找到子字符串并打印特定的lin

2024-09-29 22:00:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个文件:

[739:246050] START of MACThread:receved msg type[47]
[739:247021] PHYThrad: DSPMsgQ  Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5]
[739:247059] START of MACThread:receved msg type[47]

我需要用python打印包含“START”的行。。。你知道吗


Tags: and文件ofistypemsgsfstart
3条回答

作为命令行的一行:

代码:

python -c "import sys;[sys.stdout.write(l) for l in sys.stdin if ' START ' in l]" < file1

结果:

[739:246050] START of MACThread:receved msg type[47]
[739:247059] START of MACThread:receved msg type[47]

Stephen Rauch给出的答案很酷,但是我认为您是python的新手,所以这里有一个基本函数。你知道吗

考虑到“START”必须始终位于消息的开头,而不是介于两者之间

[739:247021] PHYThrad: START DSPMsgQ  Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5] # START at second index after split.

如果我们考虑上面的用例,下面是一个函数,它可以打印日志消息开头文件中的"START"行。你知道吗

def getStart(filename):
    with open(filename, "r") as reader:
        for lines in reader.readlines(): # get list of lines
            start =  lines.split(' ')[1] # Split with space, and check the word is "START"
            if start =='START':
                print lines

getStart("a.txt") # considering your filename is a.txt.

Output:

[739:246050] START of MACThread:receved msg type[47]

[739:247059] START of MACThread:receved msg type[47]
with open("file.txt") as f:
    lines=f.readlines()
    for i in lines:
        if i.__contains__("START"):
            print i

假设你有一个文件.txt包含数据的 您可以使用以下代码 Happing编码

相关问题 更多 >

    热门问题