上一篇提到如何用python修改文本文档,但实际遇到的问题是如何删除游戏存档中的中的一些重复内容,其实将第二个字符串换成一个空字符串“”即可:
1 def alter(file,old_str,new_str): 2 """ 3 替换文件中的字符串 4 :param file:文件名 5 :param old_str:旧字符串 6 :param new_str:新字符串 7 :return: 8 """ 9 file_data = "" 10 with open(file, "r", encoding="utf-8") as f: 11 for line in f: 12 if old_str in line: 13 line = line.replace(old_str,new_str)#line = line.replace(line,new_str)替换整行 14 file_data += line#写入file_data 15 with open(file,"w",encoding="utf-8") as f: 16 f.write(file_data)#写入文件 17 18 alter("file1", "<html>", "")
若将第13行改为line = line.replace(line,new_str),则可删除整行。
之后浏览了这篇帖子后http://www.cnblogs.com/bigberg/p/6495373.html
发现了还可以这么写
1 with open("fileread.txt","r",encoding="utf-8") as f: 2 lines = f.readlines() 3 #print(lines) 4 with open("fileread.txt","w",encoding="utf-8") as f_w: 5 for line in lines: 6 if "tasting123" in line: 7 continue 8 f_w.write(line)
不用file_data变量,直接遍历所有行,将包含指定字符串的行跳过(删除),重新写整个文本。