Python to extract data from a file

前端 未结 4 1606
暖寄归人
暖寄归人 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:20

    This works well enough for me. Your sample data is in a file called "data.txt" and the output goes to "result.txt"

    inFile = open("data.txt")
    outFile = open("result.txt", "w")
    buffer = []
    keepCurrentSet = True
    for line in inFile:
        buffer.append(line)
        if line.startswith("----"):
            #---- starts a new data set
            if keepCurrentSet:
                outFile.write("".join(buffer))
            #now reset our state
            keepCurrentSet = False
            buffer = []
        elif line.startswith("extractme"):
            keepCurrentSet = True
    inFile.close()
    outFile.close()
    

提交回复
热议问题