用Python从文件中读取多行

2024-09-26 17:54:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,其中包含我想在Python中读取的数据。文件包含以下数据:

nodCoord = 0 0 0 0.5 0 1 0.5 0 0.5 1
1 0 1 0.5 1 1 1.5 0 1.5 1
2 0 2 0.5 2 1
# Element data: element type, material, connectivities
elCon = QUAD8 1 1 4 6 7 8 5 3 2

现在我要读“nodCoord=”行和它下面所有以数字开始的行,比如“坐标”,但是我不知道会有多少行。我该怎么做?你知道吗


Tags: 文件数据datatype数字elementmaterial文本文件
1条回答
网友
1楼 · 发布于 2024-09-26 17:54:25

只要符合你的条件,就把台词读一遍。你知道吗

def extract_lines(self, file_name):
    with open(file_name) as f:
        for line in f:
            if line.startswith('nodCoord'):
                line = line.split('=')[1] # if you want to exclude the nodCoord 
                yield line
                continue
                while True:
                    if line[0].isdigit():
                        yield line
                    else:
                        break

这将为您提供一个迭代器,其中包含您想要的行,然后您可以将这些行解析为一个数组。你知道吗

还要注意的是,这将为您提供以nodCoord开头、后跟整数的每一组行。如果您对这些行的其余部分不感兴趣,或者文件中没有其他行,可以在内部代码后面的break循环中放置一个for。你知道吗

相关问题 更多 >

    热门问题