Take a look at this question. There are some solutions there.
Though I would probably go that same way Daniel and MAK suggest -- maybe make a lil' class to make things a little more flexible and explicit:
class Prepender:
def __init__(self, fname, mode='w'):
self.__write_queue = []
self.__f = open(fname, mode)
def write(self, s):
self.__write_queue.insert(0, s)
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.__write_queue:
self.__f.writelines(self.__write_queue)
self.__f.close()
with Prepender('test_d.out') as f:
f.write('string 1
')
f.write('string 2
')
f.write('string 3
')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…