How do I write to the middle of a text file while reading its contents?

前端 未结 3 1448
时光取名叫无心
时光取名叫无心 2020-12-06 22:03

First of all thanks for helping me out with moving files and for helping me in with tcl script.

Small doubt i had with python code.. as below..

impor         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 22:33

    Actually your method works but your fout is open in append mode. So this is why you can only write at the end. Here is an working example.

    # creating a file for reference
    ff = open("infiletest","w")
    pos_file = {}
    for i in range(3):
        pos_file[i] = ff.tell()
        ff.write("%s   21/1/1983\n" % i)
    ff.close()
    
    # modify the second line
    ff = open("infiletest","r+")
    ff.seek(pos_file[2])
    ff.write("%s   00/0/0000\n" % 2)
    ff.close()
    

    Note that that you overwritte the content of the file.

提交回复
热议问题