if state !_okayself __fh truncate( elselimit none for index in range(len(self - )self __seek_to_index(indexstate self __fh read( if state !_okaylimit index elsebreak if limit is not noneself __fh truncate(limit self __record_sizeself __fh flush(if the first record is blank or deletedthen they must all be blank or deleted since the previous code moved all nonblank nondeleted records to the beginning of the file and blank and deleted ones to the end in this case we can simply truncate the file to bytes if there is at least one nonblank nondeleted record we iterate from the last record backward toward the first since we know that blank and deleted records have been moved to the end the limit variable is set to the earliest blank or deleted record (or left as none if there are no blank or deleted records)and the file is truncated accordingly an alternative to doing the compacting in-place is to do it by copying to another file--this is useful if we want to make backupas the compact(method that we will review next shows def compact(selfkeep_backup=false)compactfile self __fh name $$$backupfile self __fh name bakself __fh flush(self __fh seek( fh open(compactfile"wb"while truedata self __fh read(self __record_sizeif not databreak if data[: =_okayfh write(datafh close(self __fh close(os rename(self __fh namebackupfileos rename(compactfileself __fh name