Skip to content

Commit 51cdebd

Browse files
jbrockmendelproost
authored andcommitted
BUG: unclosed file warning when passing invalid encoding (pandas-dev#30034)
1 parent 9a12000 commit 51cdebd

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

pandas/io/formats/format.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
and latex files. This module also applies to display formatting.
44
"""
55

6-
import codecs
76
from contextlib import contextmanager
87
from datetime import tzinfo
98
import decimal
@@ -495,7 +494,11 @@ def get_buffer(
495494
if hasattr(buf, "write"):
496495
yield buf
497496
elif isinstance(buf, str):
498-
with codecs.open(buf, "w", encoding=encoding) as f:
497+
with open(buf, "w", encoding=encoding, newline="") as f:
498+
# GH#30034 open instead of codecs.open prevents a file leak
499+
# if we have an invalid encoding argument.
500+
# newline="" is needed to roundtrip correctly on
501+
# windows test_to_latex_filename
499502
yield f
500503
else:
501504
raise TypeError("buf is not a file name and it has no write method")

pandas/tests/io/formats/test_format.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -3259,8 +3259,9 @@ def test_filepath_or_buffer_arg(
32593259
):
32603260
getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)
32613261
elif encoding == "foo":
3262-
with pytest.raises(LookupError, match="unknown encoding"):
3263-
getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)
3262+
with tm.assert_produces_warning(None):
3263+
with pytest.raises(LookupError, match="unknown encoding"):
3264+
getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)
32643265
else:
32653266
expected = getattr(df, method)()
32663267
getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)

0 commit comments

Comments
 (0)