How to modify lines in a file in-place with Python?

Sometimes, we want to modify lines in a file in-place with Python.

In this article, we’ll look at how to modify lines in a file in-place with Python.

How to modify lines in a file in-place with Python?

To modify lines in a file in-place with Python, we can use the in_place module.

We install it by running

pip install in-place

Then, we write

import in_place

with in_place.InPlace('data.txt') as file:
    for line in file:
        line = line.replace('test', 'testZ')
        file.write(line)

to open the file with in_place.InPlace(.

Then we loop throuygh the lines and call replace to replace the string 'test' in the line with 'testZ'.

And then we call file.write to write the line in place.

Conclusion

To modify lines in a file in-place with Python, we can use the in_place module.