def read_files(path):
#读取文件
with open(path, encoding = "utf-8") as fp:
datas = fp.readlines()
fp.close()
return datas
def change_content(path, line, content):
'''修改固定行文案,line是行数,content是添加的内容,'''
try:
datas = read_files(path)
#替换文案
if len(datas) >= int(line):
#将固定行文案替换
con_line = content + str(datas[int(line)-1])
datas[int(line)-1] = con_line
#通过writelines()函数将修改后的文案在整体修改的文件中
with open(path, "w") as fp:
fp.writelines(datas)
fp.close()
else:
print("文档不够%s行"%line)
print(read_files(path))
except FileNotFoundError as e:
print(e)
except:
print("其他异常")
change_content('111.txt', 3, "jike")