Skip to content

Commit 5c4adff

Browse files
pushkar-huei3hz
andauthored
MNT Use context managers to safely close dataset files (scikit-learn#31836)
Co-authored-by: Ved Thorat <vedthorat1029@gmail.com>
1 parent aa680bc commit 5c4adff

2 files changed

Lines changed: 14 additions & 12 deletions

File tree

sklearn/datasets/_kddcup99.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -386,12 +386,13 @@ def _fetch_brute_kddcup99(
386386
DT = np.dtype(dt)
387387
logger.debug("extracting archive")
388388
archive_path = join(kddcup_dir, archive.filename)
389-
file_ = GzipFile(filename=archive_path, mode="r")
390389
Xy = []
391-
for line in file_.readlines():
392-
line = line.decode()
393-
Xy.append(line.replace("\n", "").split(","))
394-
file_.close()
390+
391+
with GzipFile(filename=archive_path, mode="r") as file_:
392+
for line in file_.readlines():
393+
line = line.decode()
394+
Xy.append(line.replace("\n", "").split(","))
395+
395396
logger.debug("extraction done")
396397
os.remove(archive_path)
397398

sklearn/datasets/_lfw.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -169,13 +169,14 @@ def _load_imgs(file_paths, slice_, color, resize):
169169

170170
# Checks if jpeg reading worked. Refer to issue #3594 for more
171171
# details.
172-
pil_img = Image.open(file_path)
173-
pil_img = pil_img.crop(
174-
(w_slice.start, h_slice.start, w_slice.stop, h_slice.stop)
175-
)
176-
if resize is not None:
177-
pil_img = pil_img.resize((w, h))
178-
face = np.asarray(pil_img, dtype=np.float32)
172+
173+
with Image.open(file_path) as pil_img:
174+
pil_img = pil_img.crop(
175+
(w_slice.start, h_slice.start, w_slice.stop, h_slice.stop)
176+
)
177+
if resize is not None:
178+
pil_img = pil_img.resize((w, h))
179+
face = np.asarray(pil_img, dtype=np.float32)
179180

180181
if face.ndim == 0:
181182
raise RuntimeError(

0 commit comments

Comments
 (0)