DEV Community

Lakshyaraj Dash
Lakshyaraj Dash

Posted on

CRUD App Using Binary files in python

First we need to import pickle module (it is a built-in module):

import pickle
Enter fullscreen mode Exit fullscreen mode

Then we will create a function to load the file and return the data

def load_file(filename: str):
    try:
        with open(filename, 'rb') as c:
            l = []
            try:
                while True:
                    rec = pickle.load(c)
                    l.append(rec)
            except EOFError:
                return l
    except FileNotFoundError:
        open(filename, 'w')
        print(filename, "was not found, instead it was created!")
Enter fullscreen mode Exit fullscreen mode

Then we will create a function to create data

def add_data(filename: str, data: dict):
    with open(filename, "ab") as c:
        pickle.dump(data, c)

    print('Data inserted successfully!')
    opt = input("Do you want to read the data ?\n")
    if opt.lower() == 'y':
        l = load_file(filename)
        for rec in l:
            print(rec)
Enter fullscreen mode Exit fullscreen mode

Then we will create a function to update existing data

def update_data(filename: str, data: dict):
    recs = load_file(filename)
    for i in data:
        for rec in recs:
            if i in rec:
                rec[i] = data[i]
    with open(filename, "wb") as c:
        c.seek(0)
        for i in recs:
            pickle.dump(i, c)
    print('Data updated successfully!')
    opt = input("Do you want to read the data ?\n")
    if opt.lower() == 'y':
        l = load_file(filename)
        for rec in l:
            print(rec)
Enter fullscreen mode Exit fullscreen mode

Then we will create a function to delete data

def delete_data(filename: str, key: str):
    recs = load_file(filename)
    for rec in recs:
        if key in rec:
            recs.pop(recs.index(rec))
    with open(filename, "wb") as c:
        c.seek(0)
        for i in recs:
            pickle.dump(i, c)     
    print('Data deleted successfully!')
    opt = input("Do you want to read the data ?\n")
    if opt.lower() == 'y':
        l = load_file(filename)
        for rec in l:
            print(rec)
Enter fullscreen mode Exit fullscreen mode

The following fragment will run the entire program:

if __name__ == "__main__":
    filename = "student.dat"
    print('''
    1. Enter 'c' to create data
    2. Enter 'r' to read data
    3. Enter 'u' to update existing data
    4. Enter 'd' to delete data
    ''')
    ch = 'y'

    while ch == 'y':
        opt = input('Enter your option: ')
        if opt in 'crud':
            if opt == 'c':
                name = input('Enter student name: ')
                roll = input('Enter student roll no: ')
                marks = input('Enter student marks: ')

                data = {name: [roll, marks]}
                add_data(filename, data)

            if opt == 'r':
                l = load_file(filename)
                for rec in l:
                    print(rec)

            if opt == 'u':
                name = input('Enter student name (whose data is to be updated): ')
                roll = input('Enter student roll no: ')
                marks = input('Enter student marks: ')

                data = {name: [roll, marks]}
                update_data(filename, data)

            if opt == 'd':
                name = input('Enter student name (whose data is to be deleted): ')
                delete_data(filename, name)
        ch = input('Do you want to continue ?: (y for Yes or n for No)').lower()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)