Skip to content

BUG: to_pickle/read_pickle do not close user-provided file objects #35686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ I/O

- Bug in :meth:`to_csv` caused a ``ValueError`` when it was called with a filename in combination with ``mode`` containing a ``b`` (:issue:`35058`)
- In :meth:`read_csv` `float_precision='round_trip'` now handles `decimal` and `thousands` parameters (:issue:`35365`)
-
- :meth:`to_pickle` and :meth:`read_pickle` were closing user-provided file objects (:issue:`35679`)

Plotting
^^^^^^^^
Expand Down
8 changes: 6 additions & 2 deletions pandas/io/pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ def to_pickle(
try:
f.write(pickle.dumps(obj, protocol=protocol))
finally:
f.close()
if f != filepath_or_buffer:
# do not close user-provided file objects GH 35679
f.close()
for _f in fh:
_f.close()
if should_close:
Expand Down Expand Up @@ -215,7 +217,9 @@ def read_pickle(
# e.g. can occur for files written in py27; see GH#28645 and GH#31988
return pc.load(f, encoding="latin-1")
finally:
f.close()
if f != filepath_or_buffer:
# do not close user-provided file objects GH 35679
f.close()
for _f in fh:
_f.close()
if should_close:
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/io/test_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,15 @@ def python_unpickler(path):
result = python_unpickler(path)
compare_element(result, expected, typ)

# and the same for file objects (GH 35679)
with open(path, mode="wb") as handle:
writer(expected, path)
handle.seek(0) # shouldn't close file handle
with open(path, mode="rb") as handle:
result = pd.read_pickle(handle)
handle.seek(0) # shouldn't close file handle
compare_element(result, expected, typ)


def test_pickle_path_pathlib():
df = tm.makeDataFrame()
Expand Down