Skip to content

Commit 926a92c

Browse files
committed
BUG: Ensure incomplete stata files are deleted
Attempt to delete failed writes and warn if not able to delete
1 parent 87e9496 commit 926a92c

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

doc/source/whatsnew/v0.24.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1576,6 +1576,7 @@ Notice how we now instead output ``np.nan`` itself instead of a stringified form
15761576
- :func:`DataFrame.to_string()`, :func:`DataFrame.to_html()`, :func:`DataFrame.to_latex()` will correctly format output when a string is passed as the ``float_format`` argument (:issue:`21625`, :issue:`22270`)
15771577
- Bug in :func:`read_csv` that caused it to raise ``OverflowError`` when trying to use 'inf' as ``na_value`` with integer index column (:issue:`17128`)
15781578
- Bug in :func:`pandas.io.json.json_normalize` that caused it to raise ``TypeError`` when two consecutive elements of ``record_path`` are dicts (:issue:`22706`)
1579+
- Bug in :meth:`DataFrame.to_stata`, :class:`pandas.io.stata.StataWriter` and :class:`pandas.io.stata.StataWriter117` where a exception would leave a partially written and invalid dta file (:issue:`23573`)
15791580

15801581
Plotting
15811582
^^^^^^^^

pandas/io/stata.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
from collections import OrderedDict
1414
import datetime
15+
import os
1516
import struct
1617
import sys
1718
import warnings
@@ -502,6 +503,9 @@ class InvalidColumnName(Warning):
502503
alphanumerics and underscores, no Stata reserved words)
503504
"""
504505

506+
class IOWarning(Warning):
507+
pass
508+
505509

506510
def _cast_to_stata_types(data):
507511
"""Checks the dtypes of the columns of a pandas DataFrame for
@@ -2209,7 +2213,17 @@ def write_file(self):
22092213
self._write_value_labels()
22102214
self._write_file_close_tag()
22112215
self._write_map()
2212-
finally:
2216+
except Exception as exc:
2217+
self._close()
2218+
try:
2219+
if self._own_file:
2220+
os.unlink(self._fname)
2221+
except Exception:
2222+
warnings.warn('This save was not successful but {0} could not '
2223+
'be deleted. This file is not '
2224+
'valid.'.format(self._fname), IOWarning)
2225+
raise exc
2226+
else:
22132227
self._close()
22142228

22152229
def _close(self):

pandas/tests/io/test_stata.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,13 @@
1616
import pandas as pd
1717
import pandas.util.testing as tm
1818
import pandas.compat as compat
19-
from pandas.compat import iterkeys
19+
from pandas.compat import iterkeys, PY3
2020
from pandas.core.dtypes.common import is_categorical_dtype
2121
from pandas.core.frame import DataFrame, Series
2222
from pandas.io.parsers import read_csv
2323
from pandas.io.stata import (InvalidColumnName, PossiblePrecisionLoss,
24-
StataMissingValue, StataReader, read_stata)
24+
StataMissingValue, StataReader, read_stata,
25+
IOWarning)
2526

2627

2728
@pytest.fixture
@@ -1546,3 +1547,13 @@ def test_all_none_exception(self, version):
15461547
output.to_stata(path, version=version)
15471548
assert 'Only string-like' in excinfo.value.args[0]
15481549
assert 'Column `none`' in excinfo.value.args[0]
1550+
1551+
@pytest.mark.parametrize('version', [114, 117])
1552+
def test_invalid_file_not_written(self, version):
1553+
content = 'Here is one __�__ Another one __·__ Another one __½__'
1554+
df = DataFrame([content], columns=['invalid'])
1555+
expected_exc = UnicodeEncodeError if PY3 else UnicodeDecodeError
1556+
with tm.ensure_clean() as path:
1557+
with pytest.raises(expected_exc):
1558+
with pytest.warns(IOWarning):
1559+
df.to_stata(path)

0 commit comments

Comments
 (0)