I want to modify beta and n2 in Test.txt. However, f0.write() is completely rewriting all the contents. I present the current and expected outputs.
fo = open("Test.txt", "w")
fo.write( "beta=1e-2")
fo.write( "n2=5.0")
fo.close()
The contents of Test.txt is
beta=1e-1
n1=30.0
n2=50.0
The current output is
beta=1e-2n2=5.0
The expected output is
beta=1e-2
n1=30.0
n2=5.0
>Solution :
First you need to read the contents of the file and store it on a dictionary, preferably using the with statement:
data = {}
with open('Test.txt') as f:
for line in f:
line = line.strip()
# Ignore empty lines
if not line:
continue
# Split every line on `=`
key, value = line.split('=')
data[key] = value
Then, you need to modify the read dictionary to the contents you want:
data['beta'] = 1e-2
data['n2'] = 5.0
Finally, open the file again on write mode and write back the dictionary:
with open('Text.txt', 'w') as f:
for key, value in data.items():
# Join keys and values using `=`
print(key, value, sep='=', file=f)