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
def getLegend(self, filename="db_legend.csv"): """ Reads legend and returns as list. """ with open(filename, 'r') as legend_file: line = legend_file.readline() if len(line) < 1: #if legend file is empty FileProcessorExceptions.error_legend_reading() #raising exception return Parser.Parser.parseString(line)
def getValuesFromCurrentLine(self): """ Reads and returns the next record from the current line of the file. """ line = self.db_file.readline() if len(line) < 1: #if database file is empty FileProcessorExceptions.error_out_of_file() # raising exception else: self.last_line_num += 1 return Parser.Parser.parseString(string.rstrip(line))