Вариант ответа kdtrv. Эта версия сохраняет существующее содержимое файла и предлагает метод write_lines, который сохраняет порядок строк.
class Prepender(object):
def __init__(self,
file_path,
):
# Read in the existing file, so we can write it back later
with open(file_path, mode='r') as f:
self.__write_queue = f.readlines()
self.__open_file = open(file_path, mode='w')
def write_line(self, line):
self.__write_queue.insert(0,
"%s\n" % line,
)
def write_lines(self, lines):
lines.reverse()
for line in lines:
self.write_line(line)
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.__write_queue:
self.__open_file.writelines(self.__write_queue)
self.__open_file.close()
with Prepender('test_d.out') as f:
# Must write individual lines in reverse order
f.write_line('This will be line 3')
f.write_line('This will be line 2')
f.write_line('This will be line 1')
with Prepender('test_d.out') as f:
# Or, use write_lines instead - that maintains order.
f.write_lines(
['This will be line 1',
'This will be line 2',
'This will be line 3',
]
)