python中對檔案內容多行內容進行刪除
阿新 • • 發佈:2019-02-05
# Author Richard_Kong # !/usr/bin/env python # --*-- encoding:utf-8 --*-- """ 思路:將要刪除的Str儲存為新的檔案,兩個檔案對內容比較後進行刪除 """ def delete_file(file,Str): ''' :param file: :param Str: :return: ''' file_new = file+"_new" mark = 0 file_data = "" with open(file_new, mode='w', encoding="utf-8") as f_new: f_new.writelines(Str) with open(file_new, mode='r+', encoding="utf-8") as f_new: with open(file, mode='r+', encoding="utf-8") as f: for line in f: mark =0 print("line>>>:",line) f_new.seek(0) for str in f_new: print("str>>>:",str) if str in line: print("hjfbvabkj") mark = 1 print("same line",str) if mark ==1: file_data +="" else: file_data +=line with open(file, mode='w', encoding="utf-8") as f: f.writelines(file_data) Str="""{ 'bakend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } }""" delete_file("sed",Str)