不废话了 , 直接上代码:
- 下面的代码可以保证就算有中文也能正常插入正确位置
def fileInsert(file: str, want: str, insertString: str):
with open(file, "rb+") as f:
all = f.read()
index = all.index(want.encode('utf-8'))
f.seek(index)
s = f.read()
f.seek(index)
ss = insertString.encode() + s
f.write(ss)
fileInsert("11.txt", "是", "hhh")
- 效果如下:
执行前11.txt
文件内容:
你好,这里都是中文 - 执行后:
你好,这里都hhh是中文