From eb653da44227bea21384930a8379288e16268b25 Mon Sep 17 00:00:00 2001 From: Stephen Shen Date: Sat, 24 Jan 2026 22:54:13 -0500 Subject: [PATCH] Ensure files and images are properly closed --- InvoiceGenerator/generator.py | 10 ++++------ InvoiceGenerator/pdf.py | 14 +++++++------- setup.py | 3 ++- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/InvoiceGenerator/generator.py b/InvoiceGenerator/generator.py index dd0e478..9306f8f 100644 --- a/InvoiceGenerator/generator.py +++ b/InvoiceGenerator/generator.py @@ -127,9 +127,8 @@ def getContent(self): self.pdf.showPage() self.pdf.save() - f = open(self.pdffile.name) - data = f.read() - f.close() + with open(self.pdffile.name) as f: + data = f.read() os.unlink(self.pdffile.name) @@ -351,6 +350,5 @@ def gen(self, filename, pdf_invoice): invoice.addItem(item1) invoice.addItem(item2) - f = open("test.pdf", "w") - f.write(invoice.getContent()) - f.close() + with open("test.pdf", "w") as f: + f.write(invoice.getContent()) diff --git a/InvoiceGenerator/pdf.py b/InvoiceGenerator/pdf.py index 81ad911..401c794 100644 --- a/InvoiceGenerator/pdf.py +++ b/InvoiceGenerator/pdf.py @@ -227,10 +227,10 @@ def _drawAddress(self, top, left, width, height, header_string, address): frame.addFromList([story_inframe], self.pdf) if address.logo_filename: - im = Image.open(address.logo_filename) - height = 30.0 - width = float(im.size[0]) / (float(im.size[1])/height) - self.pdf.drawImage(self.invoice.provider.logo_filename, (left + 84) * mm - width, (top - 4) * mm, width, height, mask="auto") + with Image.open(address.logo_filename) as im: + height = 30.0 + width = float(im.size[0]) / (float(im.size[1])/height) + self.pdf.drawImage(self.invoice.provider.logo_filename, (left + 84) * mm - width, (top - 4) * mm, width, height, mask="auto") def _drawClient(self, TOP, LEFT): self._drawAddress(TOP, LEFT, 88, 41, _(u'Customer'), self.invoice.client) @@ -454,9 +454,9 @@ def _drawItems(self, TOP, LEFT): # noqa def _drawCreator(self, TOP, LEFT): height = 20*mm if self.invoice.creator.stamp_filename: - im = Image.open(self.invoice.creator.stamp_filename) - height = float(im.size[1]) / (float(im.size[0])/200.0) - self.pdf.drawImage(self.invoice.creator.stamp_filename, (LEFT) * mm, (TOP - 2) * mm - height, 200, height, mask="auto") + with Image.open(self.invoice.creator.stamp_filename) as im: + height = float(im.size[1]) / (float(im.size[0])/200.0) + self.pdf.drawImage(self.invoice.creator.stamp_filename, (LEFT) * mm, (TOP - 2) * mm - height, 200, height, mask="auto") path = self.pdf.beginPath() path.moveTo((LEFT + 8) * mm, (TOP) * mm - height) diff --git a/setup.py b/setup.py index 90f5e75..c2a5a67 100755 --- a/setup.py +++ b/setup.py @@ -24,7 +24,8 @@ def command(cmd): def read(fname): - return open(os.path.join(os.path.dirname(__file__), fname)).read() + with open(os.path.join(os.path.dirname(__file__), fname)) as f: + return f.read() description = ""