From a5ceb76e4356c778d3f05b6130ee1dfaa2f79534 Mon Sep 17 00:00:00 2001 From: starnakin Date: Tue, 6 Aug 2024 14:49:58 +0200 Subject: [PATCH] use with to simplify the code --- main.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/main.py b/main.py index bfadd32..7556e04 100644 --- a/main.py +++ b/main.py @@ -4,12 +4,11 @@ from Book import Book # Opening JSON file -f = open('constructor.json', encoding='utf-8') -data = json.load(f) -f.close() -f = open("style.css") -style = f.read() -f.close() +with open('constructor.json', encoding='utf-8') as f: + data = json.load(f) + +with open('style.css', encoding='utf-8') as f: + style = f.read() books = data['books'] html = "" @@ -18,13 +17,11 @@ for book_data in books: book = Book(book_data["name"], book_data["author"], book_data["description"], book_data["image"], book_data["review"], book_data["release_date"], book_data["reading_date"]) html += book.to_html() -f = open("cast.html") -text = f.read().replace("{{books}}", html).replace("{{style}}", style) -f.close() +with open('cast.html', encoding='utf-8') as f: + text = f.read().replace("{{books}}", html).replace("{{style}}", style) if len(sys.argv) > 1: - f = open(sys.argv[1], "w", encoding='utf-8') - f.write(text) - f.close() + with open(sys.argv[1], "w", encoding='utf-8') as f: + f.write(text) else: print(text) \ No newline at end of file