代码之家  ›  专栏  ›  技术社区  ›  user18994682

读取大文本文件中的块

  •  0
  • user18994682  · 技术社区  · 2 年前

    我有一个相当大的文本文件,我正在尝试根据开始和结束关键字读取一行。以下是文本文件:

    .Threshold = 0.000100
    .Threshold = 0.000100
    .Threshold = 0.000100
    .ShapesOf = 0.11
    .Viades = 0.000000
    
    .Connect U4 12345
    test1
    test2
    test3
    .EndC
    
    .Connect U5 123
    test1
    test2
    test3
    .EndC
    
    .Connect U6 12576
    test1
    test2
    test3
    .EndC
    
    .Connect U7 54367
    test1
    test2
    test3
    .EndC
    
    .Connect U8 54367
    test1
    test2
    test3
    .EndC
    

    我正在尝试使用“中断并继续”来完成它,下面是脚本:

    with open("test.txt") as ff:
        for line in ff:
            if line.startswith('.Connect U5 '):
                continue
            if line == ".EndC":
                break
            print(line)
    

    我的搜索关键字是。连接U5。我想要介于两者之间的一切 .Connect U5 接下来呢 .EndC .代码会把整个文件还给我。有什么帮助吗?

    1 回复  |  直到 2 年前
        1
  •  -1
  •   leo    2 年前

    您可以将行与结尾处的“\n”进行比较。找到开始标记后,也可以继续。

    beginOutput = false
    with open("test.txt") as ff:
        for line in ff:
            if line.startswith('.Connect U5'):
                beginOutput = true
    
            if not beginOutput:
                continue
    
            if line.strip() == ".EndC":
                break
    
            print(line)
    

    注意 strip() .这不是最好的解决方案,因为它会删除文件中的所有行。 尝试 strip() 只有以 .EndC 标记