Skip to content
Merged
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
4 changes: 3 additions & 1 deletion Doc/library/pathlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1314,7 +1314,7 @@ call fails (for example because the path doesn't exist).
.. versionadded:: 3.5


.. method:: Path.read_text(encoding=None, errors=None)
.. method:: Path.read_text(encoding=None, errors=None, newline=None)

Return the decoded contents of the pointed-to file as a string::

Expand All @@ -1329,6 +1329,8 @@ call fails (for example because the path doesn't exist).

.. versionadded:: 3.5

.. versionchanged:: 3.13
The *newline* parameter was added.

.. method:: Path.readlink()

Expand Down
4 changes: 2 additions & 2 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,12 +950,12 @@ def read_bytes(self):
with self.open(mode='rb') as f:
return f.read()

def read_text(self, encoding=None, errors=None):
def read_text(self, encoding=None, errors=None, newline=None):
"""
Open the file in text mode, read it, and close the file.
"""
encoding = io.text_encoding(encoding)
with self.open(mode='r', encoding=encoding, errors=errors) as f:
with self.open(mode='r', encoding=encoding, errors=errors, newline=newline) as f:
return f.read()

def write_bytes(self, data):
Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1878,6 +1878,21 @@ def test_read_write_text(self):
self.assertRaises(TypeError, (p / 'fileA').write_text, b'somebytes')
self.assertEqual((p / 'fileA').read_text(encoding='latin-1'), 'äbcdefg')

def test_read_text_with_newlines(self):
p = self.cls(BASE)
# Check that `\n` character change nothing
(p / 'fileA').write_bytes(b'abcde\r\nfghlk\n\rmnopq')
self.assertEqual((p / 'fileA').read_text(newline='\n'),
'abcde\r\nfghlk\n\rmnopq')
# Check that `\r` character replaces `\n`
(p / 'fileA').write_bytes(b'abcde\r\nfghlk\n\rmnopq')
self.assertEqual((p / 'fileA').read_text(newline='\r'),
'abcde\r\nfghlk\n\rmnopq')
# Check that `\r\n` character replaces `\n`
(p / 'fileA').write_bytes(b'abcde\r\nfghlk\n\rmnopq')
self.assertEqual((p / 'fileA').read_text(newline='\r\n'),
'abcde\r\nfghlk\n\rmnopq')

def test_write_text_with_newlines(self):
p = self.cls(BASE)
# Check that `\n` character change nothing
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Added *newline* parameter to :meth:`pathlib.Path.read_text`.
Patch by Junya Okabe.