Skip to content

Commit 300084d

Browse files
committed
REGR: be able to read Stata files without reading them fully into memory
Fixes pandas-dev#48700 Refs pandas-dev#9245 Refs pandas-dev#37639 Regressed in 6d1541e
1 parent 28da588 commit 300084d

File tree

4 files changed

+44
-5
lines changed

4 files changed

+44
-5
lines changed

doc/source/user_guide/io.rst

+7
Original file line numberDiff line numberDiff line change
@@ -6276,6 +6276,13 @@ values will have ``object`` data type.
62766276
``int64`` for all integer types and ``float64`` for floating point data. By default,
62776277
the Stata data types are preserved when importing.
62786278

6279+
.. note::
6280+
6281+
All :class:`~pandas.io.stata.StataReader`s, whether created by :func:`~pandas.read_stata`
6282+
(when using `iterator=True` or `chunksize`) or instantiated by hand, must be closed by
6283+
calling :meth:`~pandas.io.stata.StataReader.close` (or by using the ``with`` statement, as
6284+
in the examples above) to avoid leaking file handles.
6285+
62796286
.. ipython:: python
62806287
:suppress:
62816288

doc/source/whatsnew/v1.6.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ Performance improvements
156156
- Performance improvements to :func:`read_sas` (:issue:`47403`, :issue:`47405`, :issue:`47656`, :issue:`48502`)
157157
- Memory improvement in :meth:`RangeIndex.sort_values` (:issue:`48801`)
158158
- Performance improvement in :class:`DataFrameGroupBy` and :class:`SeriesGroupBy` when ``by`` is a categorical type and ``sort=False`` (:issue:`48976`)
159+
- Memory improvement in :class:`StataReader` when reading seekable files (:issue:`48922`)
159160

160161
.. ---------------------------------------------------------------------------
161162
.. _whatsnew_160.bug_fixes:

pandas/io/stata.py

+13-5
Original file line numberDiff line numberDiff line change
@@ -1164,15 +1164,23 @@ def __init__(
11641164
self._lines_read = 0
11651165

11661166
self._native_byteorder = _set_endianness(sys.byteorder)
1167-
with get_handle(
1167+
1168+
handles = get_handle(
11681169
path_or_buf,
11691170
"rb",
11701171
storage_options=storage_options,
11711172
is_text=False,
11721173
compression=compression,
1173-
) as handles:
1174-
# Copy to BytesIO, and ensure no encoding
1175-
self.path_or_buf = BytesIO(handles.handle.read())
1174+
)
1175+
if hasattr(handles.handle, "seekable") and handles.handle.seekable():
1176+
# If the handle is directly seekable, use it without an extra copy.
1177+
self.path_or_buf = handles.handle
1178+
self._close_file = handles.close
1179+
else:
1180+
# Copy to memory, and ensure no encoding.
1181+
with handles:
1182+
self.path_or_buf = BytesIO(handles.handle.read())
1183+
self._close_file = self.path_or_buf.close
11761184

11771185
self._read_header()
11781186
self._setup_dtype()
@@ -1192,7 +1200,7 @@ def __exit__(
11921200

11931201
def close(self) -> None:
11941202
"""close the handle if its open"""
1195-
self.path_or_buf.close()
1203+
self._close_file()
11961204

11971205
def _set_encoding(self) -> None:
11981206
"""

pandas/tests/io/test_stata.py

+23
Original file line numberDiff line numberDiff line change
@@ -1842,6 +1842,29 @@ def test_backward_compat(version, datapath):
18421842
tm.assert_frame_equal(old_dta, expected, check_dtype=False)
18431843

18441844

1845+
def test_direct_read(datapath, monkeypatch):
1846+
file_path = datapath("io", "data", "stata", "stata-compat-118.dta")
1847+
1848+
# Test that opening a file path doesn't buffer the file.
1849+
with StataReader(file_path) as reader:
1850+
# Must not have been buffered to memory
1851+
assert not isinstance(reader.path_or_buf, io.BytesIO)
1852+
assert not reader.read().empty
1853+
1854+
# Test that we use a given fp exactly, if possible.
1855+
with open(file_path, "rb") as fp:
1856+
with StataReader(fp) as reader:
1857+
assert reader.path_or_buf is fp
1858+
assert not reader.read().empty
1859+
1860+
# Test that we use a given BytesIO exactly, if possible.
1861+
with open(file_path, "rb") as fp:
1862+
with io.BytesIO(fp.read()) as bio:
1863+
with StataReader(bio) as reader:
1864+
assert reader.path_or_buf is bio
1865+
assert not reader.read().empty
1866+
1867+
18451868
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
18461869
@pytest.mark.parametrize("use_dict", [True, False])
18471870
@pytest.mark.parametrize("infer", [True, False])

0 commit comments

Comments
 (0)