Python – CRUD with CSV

contacts.csv :

NO,NAME,PHONE
1,Joe,081234
2,Richard,081234
3,Mark,081234

app.py :

import csv
import os

csv_filename = 'contacts.csv'

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def show_menu():
    clear_screen()
    print("=== CONTACT APP ===")
    print("[1] Show All")
    print("[2] Create")
    print("[3] Edit")
    print("[4] Delete")
    print("[5] Search")
    print("[0] Exit")
    print("------------------------")
    selected_menu = input("Select Menu> ")
    
    if(selected_menu == "1"):
        show_contact()
    elif(selected_menu == "2"):
        create_contact()
    elif(selected_menu == "3"):
        edit_contact()
    elif(selected_menu == "4"):
        delete_contact()
    elif(selected_menu == "5"):
        search_contact()
    elif(selected_menu == "0"):
        exit()
    else:
        print("Wrong Menu!")
        back_to_menu()

def back_to_menu():
    print("\n")
    input("Press Enter to Back")
    show_menu()


def show_contact():
    clear_screen()
    contacts = []
    with open(csv_filename) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=",")
        for row in csv_reader:
            contacts.append(row)

    if (len(contacts) > 0):
        labels = contacts.pop(0)
        print(f"{labels[0]} \t {labels[1]} \t\t {labels[2]}")
        print("-"*34)
        for data in contacts:
            print(f'{data[0]} \t {data[1]} \t {data[2]}')
    else:
        print("No Data !")
    back_to_menu()


def create_contact():
    clear_screen()
    with open(csv_filename, mode='a') as csv_file:
        fieldnames = ['NO', 'NAME', 'PHONE']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        
        no = input("No: ")
        name = input("Name: ")
        phone = input("Phone: ")

        writer.writerow({'NO': no, 'NAME': name, 'PHONE': phone})
        print("saved successfully")

    back_to_menu()


def search_contact():
    clear_screen()
    contacts = []

    with open(csv_filename, mode="r") as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            contacts.append(row)

    no = input("Search by no> ")

    data_found = []

    # mencari contact
    indeks = 0
    for data in contacts:
        if (data['NO'] == no):
            data_found = contacts[indeks]
            
        indeks = indeks + 1

    if len(data_found) > 0:
        print("Data found: ")
        print(f"Name: {data_found['NAME']}")
        print(f"Phone: {data_found['PHONE']}")
    else:
        print("Data not found")
    back_to_menu()
    


def edit_contact():
    clear_screen()
    contacts = []

    with open(csv_filename, mode="r") as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            contacts.append(row)

    print("NO \t NAME \t\t PHONE")
    print("-" * 32)

    for data in contacts:
        print(f"{data['NO']} \t {data['NAME']} \t {data['PHONE']}")

    print("-----------------------")
    no = input("Select number of contact> ")
    nama = input("New Name: ")
    telepon = input("New Phone Number: ")

    # mencari contact dan mengubah datanya
    # dengan data yang baru
    indeks = 0
    for data in contacts:
        if (data['NO'] == no):
            contacts[indeks]['NAME'] = name
            contacts[indeks]['PHONE'] = phone
        indeks = indeks + 1

    # Menulis data baru ke file CSV (tulis ulang)
    with open(csv_filename, mode="w") as csv_file:
        fieldnames = ['NO', 'NAME', 'PHONE']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        for new_data in contacts:
            writer.writerow({'NO': new_data['NO'], 'NAME': new_data['NAME'], 'PHONE': new_data['PHONE']}) 

    back_to_menu()



def delete_contact():
    clear_screen()
    contacts = []

    with open(csv_filename, mode="r") as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            contacts.append(row)

    print("NO \t NAME \t\t PHONE")
    print("-" * 32)

    for data in contacts:
        print(f"{data['NO']} \t {data['NAME']} \t {data['PHONE']}")

    print("-----------------------")
    no = input("Delete No> ")

    # mencari contact dan mengubah datanya
    # dengan data yang baru
    indeks = 0
    for data in contacts:
        if (data['NO'] == no):
            contacts.remove(contacts[indeks])
        indeks = indeks + 1

    # Menulis data baru ke file CSV (tulis ulang)
    with open(csv_filename, mode="w") as csv_file:
        fieldnames = ['NO', 'NAME', 'PHONE']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        for new_data in contacts:
            writer.writerow({'NO': new_data['NO'], 'NAME': new_data['NAME'], 'PHONE': new_data['PHONE']}) 

    print("Data has been deleted")
    back_to_menu()

if __name__ == "__main__":
    while True:
        show_menu()

Leave a Reply

Your email address will not be published. Required fields are marked *