Skip to content
Advertisement

How to use python to replace a value in a field in a text file

I have a file that looks like this:

JavaScript

I am trying to use python to change the values in the second last and last field under the [ atomtypes ] title. The deal is that I am running a code which iteratively updates this file, so I specifically want that field to be targeted, not the regular expression “2.931E-01” or “1.9173E-01”. I know we can use things like awk, but I was wondering if this is possible from python itself.

This is what I am doing so far:

JavaScript

I am changing the value in python, but I am not able to send that change to the file itself. How do I pull this off?

Any advice you have would be appreciated!

Advertisement

Answer

Use enumerate on lines so we can access current line and next line

Code

JavaScript

Test

JavaScript

File test.txt prior:

JavaScript

File test.txt after

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement