Home > Software engineering >  Edit a line in a file depending on user's input | Python
Edit a line in a file depending on user's input | Python

Time:05-02

I'm working on a contact book application to improve my python skill, so far I've created functions to add new contact, view existing contact, but I'm stuck on a function to edit them, I don't know how to tackle this task (note that editing and adding information is based on user input), currently the only information this application is recording are name, phone number and/or email (if user entered an email).

I'm storing the contacts in individual files, where file name is the contact name, and the contact are his/her information (first line is always the phone number, second line if present is the email) and I'm supposing for now that all contact have phone numbers As I think that the edit function will be similar to the add, here is the add function

def add_contact(): 
if question == 'add':
    contact_name = input('Enter the name of the contact you want to add: ')

    join_input = dir_path   "\\"   contact_name   ".txt"
    #join_input = os.joinpath(dir_path, contact_name)

    os.makedirs(dir_path, exist_ok=True)

    if os.path.exists(join_input):
        print('this contact is founded')

    else:
            
            while True:   
                contact_number = input("Enter the contact's number: ")
                
                if not contact_number.isdigit():
                    print('Type a number next time.')
                    continue
                
                else:

                    f = open(join_input, "a")
                    f.write('Phone number: '   contact_number)
                    f.write('\n')
                    f.close()


                    email_print = input('Would you like to add an email address? Type yes or no: ').lower()
                    if email_print == 'yes':
                        contact_email = input("Enter the contact's email: ")

                        f = open(join_input, "a")
                        f.write('Email Adress: ')
                        f.write(contact_email)
                        f.close()
                        
                        print('Contact', contact_name, 'is succesfuly created!')
                        break
                    
                    elif email_print == 'no':
                        print('Contact', contact_name, 'is succesfuly created!')
                        break
                
                    else:
                        continue

and here is an example of it running

Do you want to add, view, or delete contact? Enter add, view or delete:  add
Enter the name of the contact you want to add: test
Enter the contact's number: 0129309123
Would you like to add an email address? Type yes or no: yes
Enter the contact's email: [email protected]
Contact test is succesfuly created!

My progress so far in edit_contact is the following

def edit_contact():
while True:
    if question == 'edit':
        contact_edit = input('Enter the name of the contact you want to add: ')
        
        join_edit = dir_path   "\\"   contact_edit   ".txt"
        
        if os.path.exists(join_edit):
            contact_input_delete = input('Do you want to edit phone number, or email adress? Type number, or email: ').lower()
            
            if contact_input_delete == 'number':
                
                with open(join_edit, 'w') as file:
                    data = file.readlines()
                    file.writelines(data)
            
        else:
            print("This contact doesn't exists.")
            continue

if you want to see my whole function, you can check it on github: Github

CodePudding user response:

Since the file content will always be limited to two lines, you can reuse the whole add_contact() function, with a minor change, in the first open of the file use "w" argument, f = open(join_input, "w"), this will clear whatever is stored previously in the file, the second open should stay "a" to not clear the phone number. And of course you need to do some cosmetic changes (print messages), anyways the new code will be:

def edit_contact(): 
    contact_name = input('Enter the name of the contact you want to add: ')
    join_input = dir_path   "\\"   contact_name   ".txt"
    os.makedirs(dir_path, exist_ok=True)

    if not os.path.exists(join_input):#we need to reverse the condition here, if the contact is found we can edit it, otherwise we need to skip the use's input
        print('this contact does not exist')
    else:
        while True:   
            contact_number = input("Enter the contact's number: ")
            
            if not contact_number.isdigit():
                print('Type a number next time.')
                continue
                
            else:

                f = open(join_input, "w")
                f.write('Phone number: '   contact_number)
                f.write('\n')
                f.close()


                email_print = input('Would you like to add an email address? Type yes or no: ').lower()
                if email_print == 'yes':
                    contact_email = input("Enter the contact's email: ")

                    f = open(join_input, "a")
                    f.write('Email Adress: ')
                    f.write(contact_email)
                    f.close()
                        
                    print('Contact', contact_name, 'is succesfuly created!')
                    break
                    
                elif email_print == 'no':
                    print('Contact', contact_name, 'is succesfuly created!')
                    break
                
                else:
                    continue
  • Related