默认文本文件和python文件在统一目录下:
大宗师诗号文件:
冷灯看剑, 剑上几番功名? 炉香无须计苍生, 纵一川烟逝, 万丈云埋, 孤阳还照古陵。
# 将大宗师两个字加入第四行f_r=open("大宗师诗号",mode="r",encoding="utf-8")f_w=open("大宗师诗号新",mode="w",encoding="utf-8")count=1for line in f_r: if count==3: f_w.write("".join([line.strip(),"大宗师古陵逝烟\n"])) else: f_w.write(line) count+=1
#另一种写法,先放入列表,再写入文件import oslist=[]count=0with open("大宗师诗号" ,mode="r",encoding="utf8") as fr,open("大宗师诗号新",mode="w",encoding="utf8") as fw: for line in fr: if count==3: line="".join([line.strip(),"大宗师古陵逝烟\n"]) count+=1 list.append(line) for line in list: fw.write(line)os.rename("大宗师诗号","大宗师诗号旧")os.rename("大宗师诗号新","大宗师诗号")os.remove("大宗师诗号旧")
效果:
冷灯看剑, 剑上几番功名? 炉香无须计苍生, 纵一川烟逝,大宗师古陵逝烟 万丈云埋, 孤阳还照古陵。