Я не делал никаких тестов, но re.sub
мог бы быть быстрее - просто загрузите текстовый файл целиком, выполните re.sub
и запишите его:
data = '''# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9'''
import re
def fn():
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for d in add_data:
yield d
out = re.sub(r'^# aaa', lambda r, f=fn(): next(f) + r.group(0), data, flags=re.MULTILINE)
print(out)
Печать:
# Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9
С файлами ввода / вывода:
import re
def fn():
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for d in add_data:
yield d
with open('data.dat', 'r') as f_in, \
open('data.out', 'w') as f_out:
f_out.write(re.sub(r'^# aaa', lambda r, f=fn(): next(f) + r.group(0), f_in.read(), flags=re.MULTILINE))
Версия 2:
import re
def fn():
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
add_data = [s + '#aaa' for s in add_data]
for d in add_data:
yield d
with open('data.dat', 'r') as f_in, \
open('data.out', 'w') as f_out:
f_out.write(re.sub(r'^# aaa', lambda r, f=fn(): next(f), f_in.read(), flags=re.MULTILINE))