Skip to content

Issues while updating binary file #130301

@kvs-sarkar

Description

@kvs-sarkar

Bug report

Bug description:

If we write few records in the structure [NAME, DOB, CLASS, ROLLNO] eg [‘KARAN’, ‘12/01/2016, , ‘II’, 10] in a binary file. Assume we have written 7 records. Now we want some changes (in length) in any field of any of the records and update the file, suppose record number 4 in name field. If we do it then the remaining records 5th, 6th, and 7th cannot be accessed.
Reason- due to new size of the record which is updated, it loses the boundary of the remaining record.
This is a built-in issue in python.

Code
import pickle as pk

def writeRec(p):
f=open('Data.dat','ab')
pk.dump(p,f)
f.close()
print('Record Written Successfully')

def updateRec(x,y):
f=open('Data.dat','rb+')
try:
c=0
while(True):
s=f.tell()
r=pk.load(f)
if(int(r[3])==x):
#print(r)
c=1
r[0]=y
print(r)
f.seek(s,0)
pk.dump(r,f)
except:
if(c==0):
print('Record not found')
f.close()

def readRec():
f=open('Data.dat','rb')
try:
while(True):
r=pk.load(f)
print(r)
except:
f.close()
while(True):
print('Press 1 for writing')
print('Press 2 for update')
print('Press 3 for reading')
print('Press 4 for exit')
k=int(input('Enter your choice::'))

if(k==1):
    n=input('Enter name::')
    d=input('Enter DOB::')
    c=input('Enter class::')
    r=int(input('Enter roll no::'))
    x=[n,d,c,r]
    writeRec(x)
elif(k==2):
    r=int(input('Enter roll no::'))
    n=input('Enter Name::')
    updateRec(r,n)
elif(k==3):
    readRec()
elif(k==4):
    break

CPython versions tested on:

3.9

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions