diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 10cf8541effd6..4a8169c0609fd 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1049,10 +1049,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) def to_html( self, @@ -1173,7 +1175,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, @@ -1181,7 +1182,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 fa054ff7ca6c0..1a056f8cb3363 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -1547,3 +1547,10 @@ def test_col_trimming_hide_columns(): assert ctx["head"][0][c + 2]["is_visible"] == vals[1] assert len(ctx["body"][0]) == 6 # index + 2 hidden + 2 visible + trimming col + + +@pytest.mark.parametrize("format", ["html", "latex"]) +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)