Python to extract data from a file

前端 未结 4 1607
暖寄归人
暖寄归人 2020-12-06 16:09

I am trying to extract the text between that has specific text file:

----
data1
data1
data1
extractme
----
data2
data2
data2
----
data3
data3
extractme
---         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 16:34

    For Python2

    #!/usr/bin/env python
    
    with open("infile.txt") as infile:
        with open("outfile.txt","w") as outfile:
            collector = []
            for line in infile:
                if line.startswith("----"):
                    collector = []
                collector.append(line)
                if line.startswith("extractme"):
                    for outline in collector:
                        outfile.write(outline)
    

    For Python3

    #!/usr/bin/env python3
    
    with open("infile.txt") as infile, open("outfile.txt","w") as outfile:
        collector = []
        for line in infile:
            if line.startswith("----"):
                collector = []
            collector.append(line)
            if line.startswith("extractme"):
                for outline in collector:
                    outfile.write(outline)
    

提交回复
热议问题