1

I want to read in a text file, find a specific line, split the line to get the value I want to replace, and then replace that value with a new value from the script I'm using. The file looks like this:

num0  30
num1  50
num2  70

Here's the Code so far :

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()

How do I edit the above code so that the value in the line that starts with num1 is changed, rather than just appended to the top or bottom of the datafile? Where am I going wrong? Thanks.

geeb.24
  • 527
  • 2
  • 7
  • 25

1 Answers1

-1

Please check this:

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)
Learnings
  • 2,780
  • 9
  • 35
  • 55