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
3 changes: 2 additions & 1 deletion path/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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