使用python在文本文件中的两个字符串之间提取值 [英] Extract Values between two strings in a text file using python

查看:130
本文介绍了使用python在文本文件中的两个字符串之间提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含以下内容的文本文件

Lets say I have a Text file with the below content

fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk

现在我需要编写一个 Python 代码来读取文本文件并将开始和结束之间的内容复制到另一个文件中.

Now I need to write a Python code which will read the text file and copy the contents between Start and end to another file.

我写了以下代码.

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

我没有得到预期的输出我刚开始我想得到的是开始和结束之间的所有线条.不包括开始&结束.

I'm not getting the desired output as expected I'm just getting Start What I want to get is all the lines between Start and End. Excluding Start & End.

推荐答案

以防万一您的文本文件中有多个开始"和结束",这会将所有数据一起导入,不包括所有开始""s 和 "End"s.

Just in case you have multiple "Start"s and "End"s in your text file, this will import all the data together, excluding all the "Start"s and "End"s.

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start":
            copy = True
            continue
        elif line.strip() == "End":
            copy = False
            continue
        elif copy:
            outfile.write(line)

这篇关于使用python在文本文件中的两个字符串之间提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆