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.write("string 2")
f.write("string 3")
f.close()
so that the contents of out.txt
will be:
string 3
string 2
string 1
and not (like this code does):
string 1
string 2
string 3
Elaborating on Daniel DiPaolo's answer:
Simply append all the lines that you want to write to a
list
. Reverse thelist
and then write its contents into the file.You could also use a
deque
and add lines at its beginning instead of using alist
and reversing it.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:
A variation on kdtrv's answer. This version keeps the existing file contents, and offers a write_lines method that preserves line order.
You could throw a
f.seek(0)
between each write (or write a wrapper function that does it for you), but there's no simple built in way of doing this.EDIT: this doesn't work, even if you put a
f.flush()
in there it will continually overwrite. You may just have to queue up the writes and reverse the order yourself.So instead of
Maybe do something like: