1. 程式人生 > >Python中對檔案的增刪改查,多行字元的刪除

Python中對檔案的增刪改查,多行字元的刪除

# Author Richard_Kong
# !/usr/bin/env python
# --*-- encoding:utf-8 --*--
"""
修改檔案中的字元,並儲存
"""

def alter(file,old_str,new_str):
    '''
    :param file:
    :param old_str:
    :param new_str:
    :return:
    '''
    file_data = ""

    with open(file,mode='r+',encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data +=line
    with open(file,mode='w',encoding="utf-8") as f:
        f.write(file_data)
def serach(file,Str):
    '''
    :param file:
    :param Str:
    :return:
    '''
    with open(file,mode='r+',encoding="utf-8") as f:
        for index,line in enumerate(f):
            if Str in line:
                print(index+1)

def add(file,Str):
    '''
    :param file:
    :param Str:
    :return:
    '''
    with open(file, mode='a+', encoding="utf-8") as f:
        f.writelines(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)


old_str = input("Please input old String>>>:")
New_Str = input("Please input new String>>>:")
alter("sed",old_str,New_Str)
serach("sed","他們")
add("sed",Str="""arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }""")

Str="""{
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }"""
delete_file("sed",Str)