I\'m doing it like this now, but I want it to write at the beginning of the file instead.
f = open(\'out.txt\', \'a\') # or \'w\'?
f.write(\"string 1\")
f.wr
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\n')
f.write('string 2\n')
f.write('string 3\n')