write() at beginning of file?

后端 未结 4 1286
广开言路
广开言路 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 09:59

    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.

提交回复
热议问题