python 向文件指定行新增内容


file_name = unicode("文件路径例如(D:/测试文件夹/测试.txt)", "UTF-8")   # 如果不用unicode编码,下边open的时候会因为有中文而报错找不到文件。如果纯英文路径则不需要unicod
with open(file_name, 'r') as f:   #  先读文件
  lines = f.readlines()
  lines.insert(row(如果在第二行插入,那么row就是1), "要插入的内容"( 如果需要独占一行需要+ " "))
  s = ''.join(lines)  # 将列表转换为string
with open(file_name, 'w') as f:     # 写文件,开始的时候会先清空原文件,参考w的用法。如果不用with open,只是open,要注意最后将文件关闭。
  f.write(s)

原文地址:https://www.cnblogs.com/sy-gbl/p/11769798.html