file handling if not keep_backupos remove(backupfileself __fh open(self __fh name" + "this method creates two filesa compacted file and backup copy of the original file the compacted file starts out with the same name as the original but with $$tacked on to the end of the filenameand similarly the backup file has the original filename with bak tacked on to the end we read the existing file record by recordand for those records that are nonblank and nondeleted we write them to the compacted file (notice that we write the real recordthat isthe state byte plus the user recordeach time bytes and bytearray sidebar the line if data[: =_okayis quite subtle both the data object and the _okay object are of type bytes we want to compare the first byte of the data object to the ( byte_okay object if we take slice of bytes objectwe get bytes objectbut if we take single bytesaydata[ ]we get an int--the byte' value so here we compare the byte slice of data (its first bytethe state bytewith the byte _okay object (another way of doing it would be to write if data[ =_okay[ ]which would compare the two int values at the end we rename the original file as the backup and rename the compacted file as the original we then remove the backup if keep_backup is false (the defaultfinallywe open the compacted file (which now has the original filename)ready to be read or written the binaryrecordfile binaryrecordfile class is quite low-levelbut it can serve as the basis of higher-level classes that need random access to files of fixed-size recordsas we will see in the next subsection examplethe bikestock module' classes |the bikestock module uses binaryrecordfile binaryrecordfile to provide simple stock control class the stock items are bicycleseach represented by bikestock bike instanceand the entire stock of bikes is held in bikestock bikestock instance the bikestock bikestock class aggregates dictionary whose keys are bike ids and whose values are record index positionsinto binaryrecordfile binaryrecordfile here is brief example of use to get feel for how these classes workbicycles bikestock bikestock(bike_filevalue for bike in bicyclesvalue +bike value bicycles increase_stock("gekko" for bike in bicyclesif bike identity startswith(" ")