如何在文本文件中查找并替换包含for循环变量的行作为要查找的文本?

2024-09-30 22:13:35 发布

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

我试图在文本文件的一行中找到一个字符串(这是for循环变量的模式),并用列表或数组的元素替换它。我有两个for循环:一个是遍历循环变量(I=0到10),然后找到包含循环变量的字符串来替换它。两个用来遍历文本中使用查找和替换的行。通过这样做,第一次迭代的结果是正确的。也就是说,对于包含1的字符串,将替换所需的值。但在第二次迭代开始时,整个文件被删除而不被写入。有谁能帮我开导一下,我哪里做错了

如果在第一个for循环之间不打开和关闭文本文件,则返回第一次迭代的结果

import fileinput

Vertices = [[ 0.18629198,  0.    ,      0.        ],
[ 0.43554465 , 0.      ,    0.        ],
[ 5.21312944,  5.69958959,  0.        ],
[ 6.53244049,  0.97167915 , 0.        ],
[ 1.27776821, -0.28464385 , 0.        ],
[-0.81370802 , 0.         , 0.        ],
[ 5.88804502 , 6.43748454 , 0.        ],
[ 2.25384266 ,-0.50208045,  0.        ],
[ 7.52155795 , 1.11880714 , 0.        ],
[ 1.43554465 , 0.         , 0.        ],
[ 0.18629198 , 0.        ,  1.        ]]

index = 0
for points in range(11):
    MeshFile = fileinput.FileInput('blockMeshDict', inplace=True)
    for line in MeshFile:
        findText = '//Vertex_' + str(points+1) + '*'
        if findText in line:
            line = str(Vertices[index])
            index += 1
        print(line, end='')
    MeshFile.close()


####### My Text file contains the following:
vertices
(
    (-3 0 0)                                    //0
    (-1.5 0 0)                                  //Vertex_1*
    (-1.125 1.125 0)                        //Vertex_2*
    (-3 1.125 0)                                //Vertex_3*
    (-0.5 0 0)                                  //Vertex_4*
    (-0.353553390593274 0.353553390593274 0)    //Vertex_5*
    (0 0.5 0)                                   //Vertex_6*
    (0 1.5 0)                                   //Vertex_7*
    (0.353553390593274  0.353553390593274 0)    //Vertex_8*
    (1.125  1.125 0)                        //Vertex_9*
    (0.5 0 0)                                   //Vertex_10*
    (1.5 0 0)                                   //Vertex_11*
    (5 0 0)                                     //12
);

所需的输出是从顶点变量的相应条目更新顶点并写入同一文件中


Tags: 文件字符串inforindexlinepointsvertex