Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text into a text file following specific text using Python

Tags:

python

text

I have to edit some text files to include new information, but I will need to insert that information at specific locations in the file based on the surrounding text.

This doesn't work the way I need it to:

 with open(full_filename, "r+") as f:
        lines = f.readlines() 
        for line in lines:
            if 'identifying text' in line:   
                offset = f.tell()
                f.seek(offset)  
                f.write('Inserted text')

...in that it adds the text to the end of the file. How would I write it to the next line following the identifying text?

(AFAICT, this is not a duplicate of similar questions, since none of those were able to provide this answer)

like image 695
Chelonian Avatar asked Dec 27 '22 06:12

Chelonian


2 Answers

If you don't need to work in place, then maybe something like:

with open("old.txt") as f_old, open("new.txt", "w") as f_new:
    for line in f_old:
        f_new.write(line)
        if 'identifier' in line:
            f_new.write("extra stuff\n")

(or, to be Python-2.5 compatible):

f_old = open("old.txt")
f_new = open("new.txt", "w")

for line in f_old:
    f_new.write(line)
    if 'identifier' in line:
        f_new.write("extra stuff\n")

f_old.close()
f_new.close()

which turns

>>> !cat old.txt
a
b
c
d identifier
e

into

>>> !cat new.txt
a
b
c
d identifier
extra stuff
e

(Usual warning about using 'string1' in 'string2': 'name' in 'enamel' is True, 'hello' in 'Othello' is True, etc., but obviously you can make the condition arbitrarily complicated.)

like image 139
DSM Avatar answered Apr 08 '23 21:04

DSM


You could use a regex and then replace the text.

import re
c = "This is a file's contents, apparently you want to insert text"
re.sub('text', 'text here', c)
print c

returns "This is a file's contents, apparently you want to insert text here"

Not sure if it'll work for your usecase but it's nice and simple if it fits.

like image 39
BWStearns Avatar answered Apr 08 '23 23:04

BWStearns