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
Elaborating on Daniel DiPaolo's answer:
Simply append all the lines that you want to write to a list
. Reverse the list
and then write its contents into the file.
f=open('output.txt','w')
l=[]
l.append("string 1")
l.append("string 2")
l.append("string 3")
for line in l:
f.write(line)
f.close()
You could also use a deque
and add lines at its beginning instead of using a list
and reversing it.