as part as my homework one of the tasks is to update a specific line, but we are not allowed to load the whole file into the memory, but only 1 line at a time
the problem is, it writes all the info to the end of file instead of replace the same line.
i tried using seek, but kept getting errors, this is the closest i got it to somehow working.
what i want to do is take for example:
heap.update('currency', 'PKR', '123')
that will keep all the lines and just change PKR into 123 in all lines. but stay the same order.
hope someone can tell me what is my mistake. thanks!
# update a value in heap
def update(self, col_name, old_value, new_value, ):
if self.is_empty() == 0: #check if file is empty
return
i = self.findIndex(col_name) #find what column im comparing to
if i == -1: #if column out of bound
return
with open(self.name, "r") as f: #open file for read mode
while True:
temp=''
line = f.readline() #read line
if line == '': #if line is empty, we are done
break
#split line into the 4 columns
keep1 = line.split(',', 3)[0];
keep2 = line.split(',', 3)[1];
keep3 = line.split(',', 3)[2];
keep4 = line.split(',', 3)[3];
x = line.split(',')[i];
if (x == old_value): #compare value and check if its equle, if it is:
#create a new string with value
if i == 0:
temp = new_value + "," + keep2 + "," + keep3 + "," + keep4;
elif i == 1:
temp = keep1 + "," + new_value + "," + keep3 + "," + keep4;
elif i == 2:
temp = keep1 + "," + keep2 + "," + new_value + "," + keep4;
elif i == 3:
temp = keep1 + "," + keep2 + "," + keep3 + "," + new_value;
with open(self.name, "a") as ww: #write value into file
ww.write(temp)
self
def __init__(self, file_name):
self.name = file_name;
f = open(self.name, "w");
f.close();
findIndex function
def findIndex(self, col_name):
if self.is_empty() == 0:
return -1
elif col_name == 'lid':
return 0
elif col_name == 'loan_amount':
return 1
elif col_name == "currency":
return 2
elif col_name == "sector":
return 3
example of txt to read
lid,loan_amount,currency,sector
653051,300.0,PKR,Food
653053,575.0,PKR,Trns
653068,150.0,INR,Trns
653063,200.0,PKR,Arts
653084,400.0,PKR,Food
653067,200.0,INR,Agri
653078,400.0,PKR,Serv
653082,475.0,PKR,Manu
653048,625.0,PKR,Food
653060,200.0,PKR,Trns
653088,400.0,PKR,Sale
653089,400.0,PKR,Reta
653062,400.0,PKR,Clth
653075,225.0,INR,Agri
653054,300.0,PKR,Trns
653091,400.0,PKR,Reta
653052,875.0,PKR,Serv
653066,250.0,INR,Serv
653080,475.0,PKR,Serv
653065,250.0,PKR,Food
653055,350.0,PKR,Food
653050,575.0,PKR,Clth
653079,350.0,PKR,Arts
653061,250.0,PKR,Food
653074,250.0,INR,Agri
653069,250.0,INR,Cons
653056,475.0,PKR,Trns
653071,125.0,INR,Agri
653073,250.0,INR,Agri
653059,250.0,PKR,Clth
653087,400.0,PKR,Manu
653076,450.0,PKR,Reta