'Refreshing data from csv in python using pandas

I'm new to python and trying to learn it on the go, i'm tring to make a data entry phonebook using python with pandas.

There is the code I wrote:

import pandas as pd
Book = pd.read_csv(r'/Users/denisvirnik/VSCODE/Py/Projects/Book.csv')

start = True
while(start):
        print("1: Add a new contact: ")
        print("2. View contacts: ")
        print("3. Exit ")
        op = input("Which option you want to do?: ")
        if(op == "1"):
                name = input("Type the first name: ")
                lastName = input("Type the last Name: ")
                phoneNumber = input("Type the Phone Number: ")
                data = {
                'FristName,': [name],
                'LastName,': [lastName],
                'PhoneNumber,': [phoneNumber]
                }
                df = pd.DataFrame(data)#makes the data frame of the user input above
                df.to_csv(r'/Users/denisvirnik/VSCODE/Py/Projects/Book.csv', mode='a', index=False, header=False)# appends data frame to CSV file
                print("Contact successfully added.")
        if(op == "2"):
                print(Book.head())
        if(op == "3"):
                start = False

One of the options i've set is to view the phonebook(option 2 in the code), but if i enter new data into the phonebook and then try to view it without terminating the program and running it again it won't show, hope that maybe someone knows a way to refresh the data in the phonebook just as i enter new data into it.



Solution 1:[1]

You may want to use the same variable for book and df in order to enter new data and view it.

You also want to read book when op == 2.

In addition to that, you are not writing data into dataframe correctly.

I am not giving you a full answer. But, you can start with this code snippet.

import pandas as pd

start = True
while(start):
    print("1: Add a new contact: ")
    print("2. View contacts: ")
    print("3. Exit ")
    op = input("Which option you want to do?: ")
    if(op == "1"):
        book = pd.read_csv('book.csv')
        
        first_name = input("Type the first name: ")
        last_name = input("Type the last Name: ")
        phone_number = input("Type the Phone Number: ")
        
        '''
        Make sure you are writing information
        to the dataframe correctly
        '''
        # Write your code
        
        # appends data frame to CSV file
        book.to_csv('book.csv', mode='a', index=False, header=False)
        print("Contact successfully added.")
    if(op == "2"):
        book = pd.read_csv('book.csv')
        print(book.head())
    if(op == "3"):
        start = False

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeong Kim