首页 > 解决方案 > 如何在文件的特定位置插入而不是覆盖

问题描述

我正在尝试使用以下方法在文件的特定位置插入一些文本:

with open("test.txt","r+") as f:
    f.seek(5)
    f.write("B")

但这会用新数据(“B”)覆盖位置 5 的字符,而不是插入它。

例如,如果我有

AAAAAAAAAA

在文件中test.txt并运行我得到的代码AAAAABAAAA而不是AAAAABAAAAA(五个A必须在之后B

如何在文件的所需位置插入而不是覆盖?

标签: pythonpython-3.xfile

解决方案


这对我有用:

with open("test.txt","r+") as f:
    f.seek(5) #first fseek to the position
    line=f.readline() #read everything after it
    f.seek(5) #since file pointer has moved, fseek back to 5
    f.write("B") #write the letter
    f.write(line) #write the remaining part

Original : AAAAAAAAAA

After :    AAAAABAAAAA 

推荐阅读