Skip to content

Backport PR #39029: BUG: read_csv does not close file during an error in _make_reader #39160

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
Jan 14, 2021
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.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Bug fixes
~~~~~~~~~

- Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`)
-
- Bug in :func:`read_csv` not closing an opened file handle when a ``csv.Error`` or ``UnicodeDecodeError`` occurred while initializing (:issue:`39024`)
-

.. ---------------------------------------------------------------------------
Expand Down
6 changes: 5 additions & 1 deletion pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2288,7 +2288,11 @@ def __init__(self, f: Union[FilePathOrBuffer, List], **kwds):
self._open_handles(f, kwds)
assert self.handles is not None
assert hasattr(self.handles.handle, "readline")
self._make_reader(self.handles.handle)
try:
self._make_reader(self.handles.handle)
except (csv.Error, UnicodeDecodeError):
self.close()
raise

# Get columns in two steps: infer from data, then
# infer column indices from self.usecols if it is specified.
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/io/parser/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
from inspect import signature
from io import BytesIO, StringIO
import os
from pathlib import Path
import platform
from urllib.error import URLError
import warnings

import numpy as np
import pytest
Expand Down Expand Up @@ -2369,3 +2371,22 @@ def test_context_manageri_user_provided(all_parsers, datapath):
assert False
except AssertionError:
assert not reader._engine.handles.handle.closed


@td.check_file_leaks
def test_open_file(all_parsers):
# GH 39024
parser = all_parsers
if parser.engine == "c":
pytest.skip()

with tm.ensure_clean() as path:
file = Path(path)
file.write_bytes(b"\xe4\na\n1")

# should not trigger a ResourceWarning
warnings.simplefilter("always", category=ResourceWarning)
with warnings.catch_warnings(record=True) as record:
with pytest.raises(csv.Error, match="Could not determine delimiter"):
parser.read_csv(file, sep=None)
assert len(record) == 0, record[0].message