def __init__(self, filename="db_test.csv"): try: self.db_file = open(filename, 'r+') # self.db_file is file variable for DB except IOError: FileProcessorExceptions.error_file_db_opening()#raising exception self.db_filename = filename # name of DB file self.last_line_num = 0 #number of last read line in database
def applyChanges(self, change_line_no, substitute_str=""): """ Rewrites a database file if some record was deleted or modified """ old_name = self.db_filename self.db_file.close() if os.path.isfile(old_name + '.bak'): # rename data base file os.remove(old_name + '.bak') os.rename(old_name, old_name + '.bak') self.db_file = open(old_name, mode='a') # creating new database file bak_file = open(old_name+'.bak', mode='r') lines_in_base_counter = 0 for line_counter, buffer in enumerate(bak_file): # copy records to new database file if line_counter == change_line_no: if substitute_str == "": continue # deleting record else: buffer = ",".join(substitute_str) + "\n" # replaces the old record on a modified one self.db_file.write(buffer) # appending line in new DB file lines_in_base_counter += 1 bak_file.close() # close old DB file self.db_file.close() # close new DB file try: self.db_file = open(self.db_filename, 'r+') # open new DB file except IOError: FileProcessorExceptions.error_file_db_opening() return lines_in_base_counter # returns the number records in the database