Skip to content

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

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 13, 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 @@ -2297,7 +2297,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
23 changes: 23 additions & 0 deletions pandas/tests/io/parser/common/test_read_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
specific classification into the other test modules.
"""
import codecs
import csv
from io import StringIO
import os
from pathlib import Path
import warnings

import numpy as np
import pytest

from pandas.errors import EmptyDataError, ParserError
import pandas.util._test_decorators as td

from pandas import DataFrame
import pandas._testing as tm
Expand Down Expand Up @@ -208,3 +212,22 @@ def test_null_byte_char(all_parsers):
msg = "NULL byte detected"
with pytest.raises(ParserError, match=msg):
parser.read_csv(StringIO(data), names=names)


@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