Skip to content

Commit 250d216

Browse files
authored
Backport PR pandas-dev#39029: BUG: read_csv does not close file during an error in _make_reader (pandas-dev#39160)
1 parent 3969ca4 commit 250d216

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

doc/source/whatsnew/v1.2.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Bug fixes
4040
~~~~~~~~~
4141

4242
- 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`)
43-
-
43+
- Bug in :func:`read_csv` not closing an opened file handle when a ``csv.Error`` or ``UnicodeDecodeError`` occurred while initializing (:issue:`39024`)
4444
-
4545

4646
.. ---------------------------------------------------------------------------

pandas/io/parsers.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -2288,7 +2288,11 @@ def __init__(self, f: Union[FilePathOrBuffer, List], **kwds):
22882288
self._open_handles(f, kwds)
22892289
assert self.handles is not None
22902290
assert hasattr(self.handles.handle, "readline")
2291-
self._make_reader(self.handles.handle)
2291+
try:
2292+
self._make_reader(self.handles.handle)
2293+
except (csv.Error, UnicodeDecodeError):
2294+
self.close()
2295+
raise
22922296

22932297
# Get columns in two steps: infer from data, then
22942298
# infer column indices from self.usecols if it is specified.

pandas/tests/io/parser/test_common.py

+21
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@
88
from inspect import signature
99
from io import BytesIO, StringIO
1010
import os
11+
from pathlib import Path
1112
import platform
1213
from urllib.error import URLError
14+
import warnings
1315

1416
import numpy as np
1517
import pytest
@@ -2369,3 +2371,22 @@ def test_context_manageri_user_provided(all_parsers, datapath):
23692371
assert False
23702372
except AssertionError:
23712373
assert not reader._engine.handles.handle.closed
2374+
2375+
2376+
@td.check_file_leaks
2377+
def test_open_file(all_parsers):
2378+
# GH 39024
2379+
parser = all_parsers
2380+
if parser.engine == "c":
2381+
pytest.skip()
2382+
2383+
with tm.ensure_clean() as path:
2384+
file = Path(path)
2385+
file.write_bytes(b"\xe4\na\n1")
2386+
2387+
# should not trigger a ResourceWarning
2388+
warnings.simplefilter("always", category=ResourceWarning)
2389+
with warnings.catch_warnings(record=True) as record:
2390+
with pytest.raises(csv.Error, match="Could not determine delimiter"):
2391+
parser.read_csv(file, sep=None)
2392+
assert len(record) == 0, record[0].message

0 commit comments

Comments
 (0)