If you don't need to work in place, perhaps 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 compatible with Python-2.5):
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
in
>>> !cat new.txt a b c d identifier extra stuff e
(The 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 complex.)
source share