Как уже упоминал Адам, вы должны принять во внимание ограничения вашей системы, прежде чем вы сможете принять решение о подходе, достаточно ли у вас памяти, чтобы все это прочитать в память, заменить ее части и переписать.
Если вы работаете с небольшим файлом или у вас нет проблем с памятью, это может помочь:
Вариант 1)
Прочитать весь файл в память, выполнить подстановку регулярных выражений для всей или части строки и заменить ее на эту строку плюс дополнительную строку. Вам нужно убедиться, что «средняя строка» уникальна в файле, или если у вас есть метки времени в каждой строке, это должно быть довольно надежно.
# open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()
Вариант 2)
Выясните среднюю линию и замените ее на эту строку плюс дополнительную строку.
# open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "\nnew line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()