From dd6fa79af53e842d93fcf7c9853640aef6aff0e1 Mon Sep 17 00:00:00 2001 From: santhreal <64453045+santhreal@users.noreply.github.com> Date: Fri, 17 Jul 2026 23:05:55 -0700 Subject: [PATCH] fix: treat write_text linesep as a literal separator U_NEWLINE.sub passed linesep as a regex replacement template, so values like \\1 raised re.error and \\n was expanded instead of written literally. --- path/__init__.py | 3 ++- tests/test_path.py | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/path/__init__.py b/path/__init__.py index 33dd979..e8c4d98 100644 --- a/path/__init__.py +++ b/path/__init__.py @@ -899,7 +899,8 @@ def write_text( conversion. """ if linesep is not None: - text = U_NEWLINE.sub(linesep, text) + # lambda keeps linesep literal; str repl is a regex template + text = U_NEWLINE.sub(lambda _: 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 b424bb6..08043f8 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -318,6 +318,15 @@ def test_read_write(self, tmpdir): assert file.read_text(encoding='utf-8') == 'hello world' assert file.read_bytes() == b'hello world' + def test_write_text_linesep_is_literal(self, tmpdir): + file = path.Path(tmpdir) / 'filename' + file.write_text('a\nb\rc\r\nd', encoding='utf-8', linesep='\\1') + assert file.read_bytes() == b'a\\1b\\1c\\1d' + file.write_text('a\nb', encoding='utf-8', linesep='\\n') + assert file.read_bytes() == b'a\\nb' + file.write_text('a\nb', encoding='utf-8', linesep='\n') + assert file.read_bytes() == b'a\nb' + class TestPerformance: @staticmethod