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)
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With