diff --git a/newsfragments/+literal-linesep.bugfix.rst b/newsfragments/+literal-linesep.bugfix.rst new file mode 100644 index 0000000..58c1ec0 --- /dev/null +++ b/newsfragments/+literal-linesep.bugfix.rst @@ -0,0 +1 @@ +Treat the ``write_text`` line separator as literal text, preserving backslashes instead of interpreting regex replacement escapes. diff --git a/path/__init__.py b/path/__init__.py index 731e88e..39d9b38 100644 --- a/path/__init__.py +++ b/path/__init__.py @@ -897,7 +897,7 @@ def write_text( conversion. """ if linesep is not None: - text = U_NEWLINE.sub(linesep, text) + text = U_NEWLINE.sub(lambda match: linesep, text) bytes = text.encode(encoding or sys.getdefaultencoding(), errors) self.write_bytes(bytes, append=append) diff --git a/tests/test_path.py b/tests/test_path.py index 55d733c..4dff6dc 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -804,6 +804,26 @@ def test_unicode(self, tmpdir, encoding): # Check the result. assert p.bytes() == expectedBytes + @pytest.mark.parametrize( + 'linesep', [r'\n', r'\1', r'\folder', '\\', '\n', '\r\n', '', None] + ) + @pytest.mark.parametrize('append', [False, True]) + def test_write_text_literal_linesep(self, tmp_path, linesep, append): + target = Path(tmp_path / 'literal-newlines.txt') + text = 'first\nsecond\r\nthird\rfourth\u2028last' + expected = ( + text + if linesep is None + else linesep.join(['first', 'second', 'third', 'fourth', 'last']) + ) + target.write_bytes(b'existing') + + target.write_text(text, encoding='utf-8', linesep=linesep, append=append) + + assert target.read_bytes() == ( + b'existing' if append else b'' + ) + expected.encode('utf-8') + def test_chunks(self, tmpdir): p = (TempDir() / 'test.txt').touch() txt = "0123456789"