阅读行直到找到特定字符

Read lines until find specific characters

我正在尝试读取文件(读取文件中的每一行,包括字母、数字和字符)。该脚本需要正常工作,文件将类似但有一些变化。

现在,它会在发现如下一行时读取:“**HWCOLOR COMP 1066 30”。我需要脚本读取所有行,直到找到“**HW”。下面的脚本适用于解释的第一个问题。

如何编写脚本来读取文件直到找到“**HW”并停止?

我尝试用 **HW" 替换 '**HWCOLOR COMP 1066 30" 但它不起作用,因为所有字符都不匹配。

data = [] 

with open('valvebody_nodes_rec.txt') as f:
    # Skips text before the beginning of the interesting block:
    for line in f:
        if line.strip() == '*NODE, SYSTEM=R':
            break    

    # Reads text until the end of the block:
    for line in f:
        if line.strip() == '**HWCOLOR COMP       1066    30':
            break
        data.append([x.strip() for x in line.split(',')])   #intersect text

我建议使用正则表达式而不是字符串匹配。 https://docs.python.org/3/library/re.html

match = re.search('your regex here', line)
if match:
    ...

如果您不熟悉正则表达式,请查找教程,一旦您了解了基础知识,就可以玩一些 Regex Golf。正则表达式非常强大和有用,所以我强烈建议学习它们。

或者,您也可以这样做

if line.strip().startswith('**HW'):

if '**HW' in line: