Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/+literal-linesep.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Treat the ``write_text`` line separator as literal text, preserving backslashes instead of interpreting regex replacement escapes.
2 changes: 1 addition & 1 deletion path/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
20 changes: 20 additions & 0 deletions tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down