def add_record(self, book): """ Adds a new record of a book to the file.If there is a book record with the same title,author and year of publication then the book is recorded and we only change the number of copies of the recorded book.Otherwise, we add the new book. """ with open(self.file, 'r') as file: data = file.readlines() try: _file = self.file enum = enumerate(data) I = next(i for i, v in enum if Book.book_by_record(v) == book) os.rename(os.path.realpath(_file), os.path.realpath(_file)+".bak") copies = int(data[I].rstrip('\n').split('+')[-1]) book_update = book.special_record().rstrip('\n').split('+') book_update[-1] = str(int(book_update[-1]) + copies) data[I] = '+'.join(book_update) + '\n' with open(_file, 'w') as file: file.writelines(data) os.remove(os.path.realpath(self.file)+".bak") except StopIteration: data.append(book.special_record()) with open(self.file, 'a') as file: file.write(book.special_record())
def test_book_by_record(self): book = Book.book_by_record("Fall+Carl Jon+1999+Crime+3+2") self.assertEqual( "<Book Information>\nTitle:Fall\nAuthor:Carl " + "Jon\nPublished in:1999\nGenre:Crime\n" + "Rating:3.0\nNumber of copies:2\n", str(book), )
def booklist(self): """ Returns a list of the books that are recorded in the file. """ with open(self.file, 'r') as file: return [Book.book_by_record(book) for book in file.readlines()]