如果指定位置超出文件內(nèi)容長度則在末尾添加辨图,如果指定位置在文件內(nèi)容中則從中修改
如:文件a.txt中內(nèi)容為”gggg”班套,替換內(nèi)容為”gloryroad”,替換位置為1故河,則第二個(gè)g替換成gloryroad,則為”ggloryroadgg”吱韭,若替換位置為4,則超出gggg索引位置鱼的,直接在末尾添加理盆,則為”gggggloryroad”
def func(n,target_str):
? ? with open("1003.txt","r+",encoding="utf-8") as fp:
? ? ? ? word_str = fp.read()
? ? ? ? print(word_str)
? ? ? ? if n < len(word_str):
? ? ? ? ? ? word_list = list(word_str)
? ? ? ? ? ? word_list[n] = target_str
? ? ? ? ? ? print(word_list)
? ? ? ? ? ? word_str = "".join(word_list)
? ? ? ? ? ? print(word_str)
? ? ? ? ? ? fp.seek(0,0)#需要指定下游標(biāo)
? ? ? ? ? ? fp.write(word_str)
? ? ? ? else:
? ? ? ? ? ? word_str = word_str+target_str
? ? ? ? ? ? fp.seek(0,0)#需要指定下游標(biāo)
? ? ? ? ? ? fp.write(word_str)
func(2,"111")
func(50,"222")