Skip to content

Commit d616e3b

Browse files
authored
BUG: Close resources opened by pyxlsb (#39134)
1 parent e4f03f9 commit d616e3b

File tree

3 files changed

+18
-7
lines changed

3 files changed

+18
-7
lines changed

pandas/io/common.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -292,13 +292,12 @@ def _get_filepath_or_buffer(
292292

293293
# assuming storage_options is to be interpretted as headers
294294
req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options)
295-
req = urlopen(req_info)
296-
content_encoding = req.headers.get("Content-Encoding", None)
297-
if content_encoding == "gzip":
298-
# Override compression based on Content-Encoding header
299-
compression = {"method": "gzip"}
300-
reader = BytesIO(req.read())
301-
req.close()
295+
with urlopen(req_info) as req:
296+
content_encoding = req.headers.get("Content-Encoding", None)
297+
if content_encoding == "gzip":
298+
# Override compression based on Content-Encoding header
299+
compression = {"method": "gzip"}
300+
reader = BytesIO(req.read())
302301
return IOArgs(
303302
filepath_or_buffer=reader,
304303
encoding=encoding,

pandas/io/excel/_base.py

+6
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,9 @@ def load_workbook(self, filepath_or_buffer):
410410
pass
411411

412412
def close(self):
413+
if hasattr(self.book, "close"):
414+
# pyxlsb opens a TemporaryFile
415+
self.book.close()
413416
self.handles.close()
414417

415418
@property
@@ -483,6 +486,9 @@ def parse(
483486
sheet = self.get_sheet_by_index(asheetname)
484487

485488
data = self.get_sheet_data(sheet, convert_float)
489+
if hasattr(sheet, "close"):
490+
# pyxlsb opens two TemporaryFiles
491+
sheet.close()
486492
usecols = maybe_convert_usecols(usecols)
487493

488494
if not data:

pandas/tests/io/test_pickle.py

+6
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,12 @@ def __init__(self, path):
465465
else:
466466
self.headers = {"Content-Encoding": None}
467467

468+
def __enter__(self):
469+
return self
470+
471+
def __exit__(self, *args):
472+
self.close()
473+
468474
def read(self):
469475
return self.file.read()
470476

0 commit comments

Comments
 (0)