简体   繁体   English

Python,如何提取包含特定字符的行

[英]Python, how to extract lines containing a specific character

Input:输入:

=name Aa Ba Ca DD Ea
sldkclskdf
opkmnbv
=name Ab Bb Cb Db Eb
po,omome
nbnwnejkvjekw
=name Ac Bc Cc DD Ec
lkecvkkw
=name Ad Bd Cd Dd Ed
sdlkcmksldmksd
=name Ae Be Ce DD Ee
clskdjfs

Output:输出:

=name Aa Ba Ca DD Ea
sldkclskdf
opkmnbv
=name Ac Bc Cc DD Ec
lkecvkkw
=name Ae Be Ce DD Ee
clskdjfs

I'm extracting data from a file.我正在从文件中提取数据。 I want to get only lines containing a specific character(which is 'DD') and the line's information following the specific lines with 'while loop'.我只想获取包含特定字符(即“DD”)的行以及带有“while 循环”的特定行之后的行信息。

with open(file, 'r') as fr, open(file_modified, 'w') as fw:

    temp = ''
    while(line):
        line = fr.readline()

        if line.startswith('='):
            fw.write(',' + temp + '\n') 

            templist = line.strip().split()
            for element in templist:
                if element.startswith('DD'):
                    fw.write(templist) 

            temp = ''
        else:
            temp += line.strip() 
     
    fw.write(temp)

You could do it like this:你可以这样做:

INFILE = 'elold.txt'
OUTFILE = 'elnew.txt'
WRITELINE = False

with open(INFILE) as infile:
    with open(OUTFILE, 'w') as outfile:
        for line in infile:
            if line.startswith('='):
                WRITELINE = 'DD' in line
            if WRITELINE:
                outfile.write(line)

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

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