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.