python - 阅读某些单词之间的内容并打印出中间的内容。 (Python)

标签 python string python-2.7 file-io readfile

你好,我对 python 编程相当陌生,我想知道如何修复我的代码,以允许我只在普通文本文档中的两个字符串之间读取。例如,假设我有以下内容

unimportant data  
unimportant data   
unimportant data 
... ... ...   
First string     #I want to print out starting from this line                     
Important data
Important data
Important data
Important data  
Last String       #Last line I dont want to print this line.
unimportant data  
unimportant data   
unimportant data 
unimportant data  
unimportant data   
unimportant data 

到目前为止,我已经能够创建一个简单的文件 I/O 来读取一行。

data_file = open("test.txt", "r")

for line in data_file:
    if re.match("(.*)First String(.*)", line):
        print(line)

但是这只打印出第一行。

任何提示或帮助将非常感谢。

最佳答案

go = False
start = "First string"
end = "Last String"

with open('path/to/file') as infile:
    for line in infile:
        line = line.strip()
        if line == start: go = True
        elif line == end:
            go = False
            continue
        if go: print(line)

如果您只是寻找关键字,而不是匹配整行:

go = False
start = "First string"
end = "Last String"

with open('path/to/file') as infile:
    for line in infile:
        line = line.strip()
        if start in line: go = True
        elif end in line:
            go = False
            continue
        if go: print(line)

关于python - 阅读某些单词之间的内容并打印出中间的内容。 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32017495/

相关文章:

python - 导入错误 : No module named 'config.settings' ; 'config' is not a package

Python:在列表中查找

python - 通过python正则表达式忽略ip地址第一个八位字节中的这两个数字(以127或0开头)

python - 从此列表中递归地将所有文件和文件夹设置为 777

python-2.7 - 尝试使用 kerberos winrm 连接到 Windows winRM

python - 改进对 Twitter 查询的列表理解

c# - string.Equals (c#) 的文化参数何时真正产生影响的示例?

swift - 如何将Character类型注解转成String类型注解?

java - java中如何将字符串转换为 boolean 值?

python - cxfreeze aiohttp 无法导入兼容