python任意文本文件内指定位置插入一段字符串代码

#向文件中第100个字符部位插入一段字符串
addr=r'c:/test/test.txt'#文件地址
s='hello nice to see you'#插入的字符
pos=200;#插入的位置
fi=open(addr,'r+',encoding='utf8')
strall=fi.read()
str1=strall[0:pos]
fi.seek(0)
str2=strall[pos:len(strall)]
str3=str1+s+str2;
fi.seek(0)
fi.write(str3);
fi.close()
print('不出意外已经好了');

python任意文本文件内指定位置插入一段字符串代码_第1张图片

你可能感兴趣的:(python)