Skip to main content
 首页 » 编程设计

python之如何用Python中的其他值替换文件中的值

2025年05月04日6kerrycode

我正在用 Python 编写一个程序,从文件中的表中搜索 column1 中的 value1,如果它存在,则替换 value2 在表格的同一行中。该表的行和列中的值由空格分隔。文件的前三行包含文本,因此在我的代码中我跳过了前三行并从第一列的第一个元素开始搜索。我已经用 python 编写了代码(python 初学者)。我正在使用替换函数将 value2 替换为新值。没有错误,但替换方法不起作用。该值未在文件中修改。我在 stackoverflow 中搜索了类似的问题并实现了它,但无法找到正确的输出。如果你能帮我解决这个问题,那将会很有帮助。提前致谢。

跳过前三个标题行...

0  2.00000E-01  2.00000E+00  1.00000E-01  1.00000E-01  0.00000E+00  1.00000E-01    5315.58609617651 
5  8.61341E-02  9.32377E-01  1.03878E-01  9.66092E-02  0.00000E+00  1.31608E-01    4874.21137697405 
10  9.01592E-02  1.01589E+00  1.02249E-01  1.16872E-01  0.00000E+00  1.37603E-01    4868.99427672864 
14  9.16065E-02  1.02727E+00  1.02914E-01  1.15918E-01  0.00000E+00  1.34975E-01    4868.85701581641 
-1000000000  9.16065E-02  1.02727E+00  1.02914E-01  1.15918E-01  0.00000E+00  1.34975E-01    4868.85701581641 
-1000000001  4.76910E-03  5.52689E-02  9.21654E-03  2.79153E-02  1.00000E+10  2.92135E-02   0.000000000000000E+000 
-1000000004  0.00000E+00  0.00000E+00  3.20802E-01  3.40467E-01  0.00000E+00  3.67390E-01   0.000000000000000E+000 
-1000000005  0.00000E+00  0.00000E+00  1.43648E-02  4.09956E-02  1.00000E+10  3.97582E-02   0.000000000000000E+000 

我的代码: #Python 导入系统 # 打开文件 foce.ext 并读取内容

iteration=[] 
obj_value=[] 
with open('ex_foce.ext','r+') as file: 
#to skip first three lines and store the elements in 1st and 8th column in two arrays 
    line1=file.readlines()[2:] 
 
    for line in line1: 
        if line: 
            information=line.split() 
            iteration.append(information[0]) 
            obj_value.append(information[7]) 
    print(line1) 
 
    print(iteration) 
 
    print(obj_value) 
    pos=iteration.index('-1000000000') 
    print(pos) 
    #replacing value2 by 1.0 
    obj_value[pos]=1.0 
    print(obj_value[pos]) 
    old_value=obj_value[pos] 
    line_number=pos 
    x=line1[line_number] 
    file.write(x.replace( str(old_value), "1.0" )) 
 
file.close() 

请您参考如下方法:

当您执行 line1=file.readlines()[2:] 时,“光标”会移动到文件末尾。然后你要求用替换值写入行,那么它不是在文件末尾复制而不是就地修改吗?也许您在编写之前错过了 file.seek(...) 调用。