From 85ec6eb251a354fa6e3a4e1f2b37a0fa94f962d7 Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Thu, 17 Nov 2016 06:21:50 -0800 Subject: [PATCH] Close file after finished reading in ImageFont._load_pilfont() Fixes some "ResourceWarning: unclosed file ..." when running tests with warnings enabled. --- PIL/ImageFont.py | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/PIL/ImageFont.py b/PIL/ImageFont.py index 6bd48dd6e..49494b33f 100644 --- a/PIL/ImageFont.py +++ b/PIL/ImageFont.py @@ -62,23 +62,22 @@ class ImageFont(object): def _load_pilfont(self, filename): - fp = open(filename, "rb") - - for ext in (".png", ".gif", ".pbm"): - try: - fullname = os.path.splitext(filename)[0] + ext - image = Image.open(fullname) - except: - pass + with open(filename, "rb") as fp: + for ext in (".png", ".gif", ".pbm"): + try: + fullname = os.path.splitext(filename)[0] + ext + image = Image.open(fullname) + except: + pass + else: + if image and image.mode in ("1", "L"): + break else: - if image and image.mode in ("1", "L"): - break - else: - raise IOError("cannot find glyph data file") + raise IOError("cannot find glyph data file") - self.file = fullname + self.file = fullname - return self._load_pilfont_data(fp, image) + return self._load_pilfont_data(fp, image) def _load_pilfont_data(self, file, image):