在Python中替换文本文件中的字符串

在Python中替换文本文件中的字符串,python,Python,我想读入一个文本文件,找到一个特定的行,拆分该行以获得我要替换的值,然后用我正在使用的脚本中的新值替换该值。该文件如下所示: num0 30 num1 50 num2 70 以下是迄今为止的代码: newval= 20 with open(file, 'r+') as f: for line in open(file): if line.startswith('num1'): val = line.strip().split()[1]

我想读入一个文本文件,找到一个特定的行,拆分该行以获得我要替换的值,然后用我正在使用的脚本中的新值替换该值。该文件如下所示:

num0  30
num1  50
num2  70
以下是迄今为止的代码:

newval= 20
with open(file, 'r+') as f:
    for line in open(file):
        if line.startswith('num1'):
            val = line.strip().split()[1]
            line = line.replace(str(val),str(new_val))
     f.write(line + "\n")
 f.close()
如何编辑上面的代码,以便更改以num1开头的行中的值,而不是仅仅附加到数据文件的顶部或底部?我哪里做错了?谢谢。

请检查以下内容:

import sys, fileinput

File = r"D:\Sunil_Work\File.txt"
Replace_What = 'num1'
New_Value = '20'

for Line in fileinput.input(File, inplace=True):  #:- Entire Line Replace
    if Replace_What in Line:
        Line = Line.replace(Line, Replace_What + ' ' + New_Value + '\n')
    sys.stdout.write(Line)

获取列表中的所有行,替换列表中的项目并将其重写回文件。您可能希望查看以下内容: