Yakkers21 Yakkers21 - 1 month ago 9
Python Question

Exchanging out specific lines of a file

I don't know if this should be obvious to the more tech savvy among us but is there a specific way to read a line out of a text file, then edit it and insert it back into the file in the original location? I have looked on the site but all the solutions I find seem to be for python 2.7.

Below is an example of what I am looking for:

with open example.txt as file:
for line in file:
if myline in file:
file.edit("foo","fah")

Answer

In 95% cases, replacing data (e.g. text) in a file usually means

  1. Read the file in chunks, e.g. line-by-line
  2. Edit the chunk
  3. Write the edited chunk to a new file
  4. Replace the old file with a new file.

So, a simple code will be:

import os

with open(in_path, 'r') as fin:
    with open(temp_path, 'w') as fout:
        for line in fin:
            line.replace('foo', 'fah')
            fout.write(line)

os.rename(temp_path, in_path)

Why not in-place replacements? Well, a file is a fixed sequence of bytes, and the only way to grow it - is to append to the end of file. Now, if you want to replace the data of the same length - no problems. However if the original and new sequences' lengths differ - there is a trouble: a new sequence will be overwriting the following characters. E.g.

original: abc hello abc world
replace abc -> 12345
result: 12345ello 12345orld