write() at beginning of file?

后端 未结 4 1301
广开言路
广开言路 2020-12-09 09:43

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         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-09 10:15

    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

    f.write("string 1")
    f.write("string 2")
    f.write("string 3")
    

    Maybe do something like:

    writeList = []
    writeList.append("string 1\n")
    writeList.append("string 2\n")
    writeList.append("string 3\n")
    writeList.reverse()
    f.writelines(writeList)
    

提交回复
热议问题