替换信息

时间:2019-11-29 22:38:47

标签: python loops text-files

我想替换旧行中已编辑的新信息,而又不会丢失其他用户的信息,但是我不知道如何在def edit_sup()中进行操作。我尝试编译但出现错误:IndexError: list index out of range

def create_sup():
    with open("supplier.txt","a+") as file:
        sup_name = input("Enter New Supplier's Name : ")
        sup_idgen = random.randint(0,9999)
        sup_idd = sup_idgen
        sup_id = str(sup_idd)
        print("Supllier ID : ",sup_id)
        sup_city = input("Enter New Supplier's City : ")
        sup_contact = input("Enter New Supplier's Contact Number : ")
        sup_email = input("Enter New Supplier's Email : ")
        columnsup = sup_name +" "+ sup_id +" "+ sup_city+" "+ sup_contact+" "+sup_email
        file.write(columnsup+"\n")    
def edit_sup():
        with open("supplier.txt", "a+") as file:
            data = file.read().split("\n")
            supp_id = input("Enter the ID of the supplier you want to edit : ")
            for line in data:
                lines = line.split()
                if supp_id in line:
                    print("-" * 60)
                    print('                    1  update supplier name')
                    print("-" * 60)
                    print('                    2  update supplier id')
                    print("-" * 60)
                    print('                    3  update supplier city')
                    print("-" * 60)
                    print('                    4  update supplier contact no')
                    print("-" * 60)
                    print('                    5  update supplier email id')
                    print("-" * 60)
                    choice = int(input('Please Select Menu [1-5] : '))
                    if (choice == 1):
                        lines[0] = input("Enter Updated Name : ")
                    elif (choice == 2):
                        lines[1] = int(input("Enter Updated ID : "))
                    elif (choice == 3):
                        lines[2] = input("Enter Updated City : ")
                    elif (choice == 4):
                        lines[3] = int(input("Enter Updated Contact : "))
                    elif (choice == 5):
                        lines[4] = int(input("Enter Updated Email ID : "))
                    else:
                        print("Incorrect Menu! Please Try Again\n")
                liness = lines[0] +" "+ lines[1] +" "+ lines[2]+" "+ lines[3]+" "+lines[4] ##have a problem
                file.write(liness+"\n")

1 个答案:

答案 0 :(得分:0)

import random

def create_sup():
    with open("supplier.txt", "a+") as file:
        struct = dict(
            sup_id = str(random.randint(0, 9999)), # probably you also wanna check for ID will be unique ?
            sup_name = '',
            sup_city = '',
            sup_contact = '',
            sup_email = ''
        )
        print("Supllier ID : ", struct['sup_id'] )
        struct['sup_name'] = input("Enter New Supplier's Name : ")   
        struct['sup_city'] = input("Enter New Supplier's City : ")
        struct['sup_contact'] = input("Enter New Supplier's Contact Number : ")
        struct['sup_email'] = input("Enter New Supplier's Email : ")
        raw_record = ' '.join( struct.values() )
        file.write(raw_record + '\n')  

def organize_data(raw):
    struct = dict(
        sup_id = '',
        sup_name = '',
        sup_city = '',
        sup_contact = '',
        sup_email = ''
    )
    return  dict( zip(struct.keys(), raw.split(" ")) )

def print_edit_info():
    def format(txt):
        separator = '-' * 60 + '\n'
        spacer =  ' ' * 20
        return f'{separator}{spacer}{txt}'
    messages = (
        format('1  update supplier id'),
        format('2  update supplier name'),
        format('3  update supplier city'),
        format('4  update supplier contact no'),
        format('5  update supplier email id'),
        "-" * 60
    )
    print('\n'.join(messages))

def prepare_records(raw_history_list):
    return '\n'.join([ ' '.join( record.values() ) for record in raw_history_list ])

def edit_sup():
    with open("supplier.txt", "r+") as file:
        data = file.read().split("\n")
        dataset = dict()
        for raw in data: 
            if raw:
                parsed_raw = organize_data(raw)
                key = parsed_raw['sup_id']
                if key in dataset:
                    dataset[key].append(parsed_raw)
                else:
                    dataset[key] = [ parsed_raw ]

        supp_id = input("Enter the ID of the supplier you want to edit : ")
        record = dataset.get(supp_id)
        if record:
            tmp_obj = record[-1].copy()
            print_edit_info()
            choice = int(input('Please Select Menu [1-5] : '))
            field_to_edit = {
                1: ('sup_id', int, "Enter Updated ID : "), # for keep data organized in file better to not allowd to edit ID
                2: ('sup_name', str, "Enter Updated Name : "), 
                3: ('sup_city', str, "Enter Updated City : "),
                4: ('sup_contact', int, "Enter Updated Contact : "), 
                5: ('sup_email', str, "Enter Updated Email ID : "),
            }.get(choice)
            if not field_to_edit:
                return print('Incorrect Menu! Please Try Again\n')
            tmp_obj[field_to_edit[0]] = field_to_edit[1](input(field_to_edit[2]))
            dataset[record[-1]['sup_id']].append(tmp_obj)

            file.seek(0)
            file.write(  
                '\n'.join( 
                    [ 
                        prepare_records(l) for l in dataset.values() 
                    ]
                )
            )

请注意,这段代码sup_id在原始代码中排在第一位,在您的代码中排在第二位,还需要一种更好的方式来创建ID,然后只使用rand,否则就需要一条新记录与现有ID相同的ID将被解析为现有记录的数据更新