Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modifying specific contents of a text file in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading