Skip to content

Commit 3332540

Browse files
bashtageTomAugspurger
authored andcommitted
BUG: Ensure incomplete stata files are deleted (pandas-dev#24319)
1 parent f5c4799 commit 3332540

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

doc/source/whatsnew/v0.24.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1579,6 +1579,7 @@ Notice how we now instead output ``np.nan`` itself instead of a stringified form
15791579
- :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`)
15801580
- 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`)
15811581
- 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`)
1582+
- 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`)
15821583
- Bug in :meth:`DataFrame.to_stata` and :class:`pandas.io.stata.StataWriter117` that produced invalid files when using strLs with non-ASCII characters (:issue:`23573`)
15831584

15841585
Plotting

pandas/io/stata.py

+14-2
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
@@ -23,7 +24,8 @@
2324
from pandas._libs.tslibs import NaT, Timestamp
2425
from pandas._libs.writers import max_len_string_array
2526
from pandas.compat import (
26-
BytesIO, lmap, lrange, lzip, range, string_types, text_type, zip)
27+
BytesIO, ResourceWarning, lmap, lrange, lzip, range, string_types,
28+
text_type, zip)
2729
from pandas.util._decorators import Appender, deprecate_kwarg
2830

2931
from pandas.core.dtypes.common import (
@@ -2209,7 +2211,17 @@ def write_file(self):
22092211
self._write_value_labels()
22102212
self._write_file_close_tag()
22112213
self._write_map()
2212-
finally:
2214+
except Exception as exc:
2215+
self._close()
2216+
try:
2217+
if self._own_file:
2218+
os.unlink(self._fname)
2219+
except Exception:
2220+
warnings.warn('This save was not successful but {0} could not '
2221+
'be deleted. This file is not '
2222+
'valid.'.format(self._fname), ResourceWarning)
2223+
raise exc
2224+
else:
22132225
self._close()
22142226

22152227
def _close(self):

pandas/tests/io/test_stata.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import pandas as pd
1717
import pandas.util.testing as tm
1818
import pandas.compat as compat
19-
from pandas.compat import iterkeys, PY3
19+
from pandas.compat import iterkeys, PY3, ResourceWarning
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
@@ -1547,6 +1547,16 @@ def test_all_none_exception(self, version):
15471547
assert 'Only string-like' in excinfo.value.args[0]
15481548
assert 'Column `none`' in excinfo.value.args[0]
15491549

1550+
@pytest.mark.parametrize('version', [114, 117])
1551+
def test_invalid_file_not_written(self, version):
1552+
content = 'Here is one __�__ Another one __·__ Another one __½__'
1553+
df = DataFrame([content], columns=['invalid'])
1554+
expected_exc = UnicodeEncodeError if PY3 else UnicodeDecodeError
1555+
with tm.ensure_clean() as path:
1556+
with pytest.raises(expected_exc):
1557+
with tm.assert_produces_warning(ResourceWarning):
1558+
df.to_stata(path)
1559+
15501560
def test_strl_latin1(self):
15511561
# GH 23573, correct GSO data to reflect correct size
15521562
output = DataFrame([[u'pandas'] * 2, [u'þâÑÐŧ'] * 2],

0 commit comments

Comments
 (0)