Skip to content

Close FastParquet file even on error #46556

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 8 commits into from
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes from 6 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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,8 @@ I/O
- Bug in :func:`read_parquet` when ``engine="pyarrow"`` which caused partial write to disk when column of unsupported datatype was passed (:issue:`44914`)
- Bug in :func:`DataFrame.to_excel` and :class:`ExcelWriter` would raise when writing an empty DataFrame to a ``.ods`` file (:issue:`45793`)
- Bug in Parquet roundtrip for Interval dtype with ``datetime64[ns]`` subtype (:issue:`45881`)
- Bug in :func:`read_excel` when reading a ``.ods`` file with newlines between xml elements(:issue:`45598`)
- Bug in :func:`read_excel` when reading a ``.ods`` file with newlines between xml elements (:issue:`45598`)
- Bug in :func:`read_parquet` when ``engine="fastparquet"`` where the file was not closed on error (:issue:`46555`)

Period
^^^^^^
Expand Down
13 changes: 6 additions & 7 deletions pandas/io/parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,13 +349,12 @@ def read(
)
path = handles.handle

parquet_file = self.api.ParquetFile(path, **parquet_kwargs)

result = parquet_file.to_pandas(columns=columns, **kwargs)

if handles is not None:
handles.close()
return result
try:
parquet_file = self.api.ParquetFile(path, **parquet_kwargs)
return parquet_file.to_pandas(columns=columns, **kwargs)
finally:
if handles is not None:
handles.close()


@doc(storage_options=_shared_docs["storage_options"])
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/io/test_parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -1155,3 +1155,13 @@ def test_use_nullable_dtypes_not_supported(self, fp):
df.to_parquet(path)
with pytest.raises(ValueError, match="not supported for the fastparquet"):
read_parquet(path, engine="fastparquet", use_nullable_dtypes=True)

def test_close_file_handle_on_read_error(self):
df = pd.DataFrame({"a": [1, 2]})
with tm.ensure_clean() as path:
df.to_parquet(path)
with open(path, 'r+b') as f:
f.seek(16)
f.write(b'breakit')
with pytest.raises(Exception): # Not important which exception
read_parquet(path, engine="fastparquet")