diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index 0c326e15d90ed..23c8ad63bf7bb 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -16,7 +16,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`DataFrame.nsmallest` led to wrong results when ``np.nan`` in the sorting column (:issue:`46589`) - Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`) -- +- Fixed regression is :meth:`.Styler.to_latex` and :meth:`.Styler.to_html` where ``buf`` failed in combination with ``encoding`` (:issue:`47053`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 54568d5cd18bb..90642ff2bb3fc 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1153,10 +1153,12 @@ def to_latex( clines=clines, ) - encoding = encoding or get_option("styler.render.encoding") - return save_to_buffer( - latex, buf=buf, encoding=None if buf is None else encoding + encoding = ( + (encoding or get_option("styler.render.encoding")) + if isinstance(buf, str) # i.e. a filepath + else encoding ) + return save_to_buffer(latex, buf=buf, encoding=encoding) @Substitution(buf=buf, encoding=encoding) def to_html( @@ -1273,7 +1275,6 @@ def to_html( if caption is not None: obj.set_caption(caption) - encoding = encoding or get_option("styler.render.encoding") # Build HTML string.. html = obj._render_html( sparse_index=sparse_index, @@ -1281,7 +1282,7 @@ def to_html( max_rows=max_rows, max_cols=max_columns, exclude_styles=exclude_styles, - encoding=encoding, + encoding=encoding or get_option("styler.render.encoding"), doctype_html=doctype_html, **kwargs, ) diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 4615f3ff50cbd..60800bc794592 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -1557,3 +1557,10 @@ def test_no_empty_apply(mi_styler): # 45313 mi_styler.apply(lambda s: ["a:v;"] * 2, subset=[False, False]) mi_styler._compute() + + +@pytest.mark.parametrize("format", ["html", "latex", "string"]) +def test_output_buffer(mi_styler, format): + # gh 47053 + with open(f"delete_me.{format}", "w") as f: + getattr(mi_styler, f"to_{format}")(f)