在python中从具有不同行和列大小的文本文件中读取值

2024-10-02 20:43:10 发布

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

我也读过其他类似的帖子,但它们对我的情况似乎不起作用。因此,我把它新贴在这里。在

我有一个文本文件,它有不同的行和列大小。我对具有特定参数的值行感兴趣。E、 在下面的示例文本文件中,我需要每行的最后两个值,其中第二个位置的数字为“1”。也就是说,我希望值“1,101”,“101,2”,“2,102”和“102,3”从值“101到104”开始,因为它们在第二个位置有数字“1”。在

$MeshFormat
2.2 0 8
$EndMeshFormat
$Nodes
425
.
.
$EndNodes
$Elements
630
.
97 15 2 0 193 97
98 15 2 0 195 98
99 15 2 0 197 99
100 15 2 0 199 100
101 1 2 0 201 1 101
102 1 2 0 201 101 2
103 1 2 0 202 2 102
104 1 2 0 202 102 3
301 2 2 0 303 178 78 250
302 2 2 0 303 250 79 178
303 2 2 0 303 198 98 249
304 2 2 0 303 249 99 198
.
.
.
$EndElements

问题是,对于我在下面提到的代码,它从'101'开始,但是它从其他行读取值直到'304'或更多。我做错了什么?或者有人有更好的方法来解决这个问题?在

^{pr2}$

*编辑:用于查找参数的代码段如下:

# anz_elemente_ueberg_gmsh is another parameter that is found out 
# from a previous piece of code and '$EndElements' is what 
# is at the end of the text file "mesh_outer_region.msh".

input_file = open(os.path.join(gmsh_path, "mesh_outer_region.msh"), "r")
for i, line in enumerate(input_file):                     
    if line.strip() == anz_elemente_ueberg_gmsh:
        break

for i, line in enumerate(input_file):                    
    if line.strip() == '$EndElements':                    
        break

    element_list = line.strip().split()                   
    if element_list[1] == '1':                            


        two_noded_elem_start = element_list[0]                       
        two_noded_elem_start = int(two_noded_elem_start)            
        break
input_file.close()

Tags: inputifislineelementstartlistfile
1条回答
网友
1楼 · 发布于 2024-10-02 20:43:10
>>> with open('filename') as fh:             # Open the file
...    for line in fh:                       # For each line the file
...        values = line.split()             # Split the values into a list
...        if values[1] == '1':              # Compare the second value
...            print values[-2], values[-1]  # Print the 2nd from last and last
1 101
101 2
2 102
102 3

相关问题 更多 >