如何使用 python 在文件开头追加文件,seek(0,0) 不起作用

How to append the file in the beginning of file using python, seek(0,0) is not working

我在python写程序。我想保存更新的文件以保持版本更改。如何在文件开头追加行。我试过 seek(0,0) 但它不起作用

代码有什么需要修改的吗

firfox.txt

 firefox-x 46.0:
 google 5.1.0.1:
     - request

file.py

 import re
 rx = r'\d+(?=:$)'
 with open('firfox.txt', 'r') as fr:
     data = fr.read()
     fr.seek(0,0)
     with open('firfox.txt', 'a') as fw:
         fw.seek(0,0)
         fw.write('\n')
         fw.write(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))

我写过其他file.py

import re
rx = r'\d+(?=:$)'
with open('firfox.txt', 'r+') as fr:
    data = fr.read()
    fr.seek(0,0)
    fr.write(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))
    fr.write(data)

这里多行重复,就像我执行两次一样 firefox-x 46.0: 行来了两次

新预期 firfox.txt 如下所示。执行一次

 firefox-x 46.1:
 google 5.1.0.1:
     - request
 firefox-x 46.0:
 google 5.1.0.1:
     - request

如果再次执行 python 预期输出的文件如下。

 firefox-x 46.2:
 google 5.1.0.1:
     - request
 firefox-x 46.1:
 google 5.1.0.1:
     - request
 firefox-x 46.0:
  google 5.1.0.1:
     - request

试试这个:

 import re
 rx = r'\d+(?=:$)'
 with open('firfox.txt', 'r') as fr:
     data = fr.read()
     fr.close()
     with open('firfox.txt', 'w') as fw: # w mode always start from beginning 
         fw.write(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))   
         fw.write('\n')
         fw.write(data) 
         fw.close()

写入新数据后只需写入以前的文本文件数据