Skip to content Skip to sidebar Skip to footer

How To Write To A Specific Line Of A File?

Let's say I have a text file Line 1 Line 2 Line 3 I read through it and decide to change Line 2 to Line Two. Can I do that elegantly in Python without simply rewriting the file wi

Solution 1:

A file is a sequence of bytes. If you want to change something in the middle that requires more or fewer bytes to express, the rest of the file needs to resize.

Because a file is a physical sequence of bytes on a storage medium, that means you need to rewrite the entire rest of the file. In other words, you need to move over everything following line 2.

In practice, that means rewriting the file, as that is much easier to achieve.

Solution 2:

You want the power of in-place editing, which the fileinput module offers:

inplace-edit.py:

import sys
import fileinput

for line in fileinput.input(sys.argv[1], inplace=1):
    line = line.rstrip() # Remove the new lineif line == 'Line 2':
        line = 'Line two'print line

data.txt:

Line 1
Line 2
Line 3

To run it:

python inplace-edit.py data.txt

The resulting data.txt:

Line 1
Line two
Line 3

Post a Comment for "How To Write To A Specific Line Of A File?"