summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorJunya Okabe <86868255+Okabe-Junya@users.noreply.github.com>2023-11-21 22:32:38 (GMT)
committerGitHub <noreply@github.com>2023-11-21 22:32:38 (GMT)
commit9d70831cb7127855a8bf83b585525f13cffb9f59 (patch)
treec0fdcdc9515a5742c27ebab65ef377ecf37849ec /Lib
parentd857d5331a3326c77f867d837014d774841017a9 (diff)
downloadcpython-9d70831cb7127855a8bf83b585525f13cffb9f59.zip
cpython-9d70831cb7127855a8bf83b585525f13cffb9f59.tar.gz
cpython-9d70831cb7127855a8bf83b585525f13cffb9f59.tar.bz2
gh-110745: add a newline argument to pathlib.Path.read_text (#110880)
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com> Co-authored-by: Barney Gale <barney.gale@gmail.com>
Diffstat (limited to 'Lib')
-rw-r--r--Lib/pathlib.py4
-rw-r--r--Lib/test/test_pathlib.py15
2 files changed, 17 insertions, 2 deletions
diff --git a/Lib/pathlib.py b/Lib/pathlib.py
index 73f87b9..9bce532 100644
--- a/Lib/pathlib.py
+++ b/Lib/pathlib.py
@@ -950,12 +950,12 @@ class _PathBase(PurePath):
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):
diff --git a/Lib/test/test_pathlib.py b/Lib/test/test_pathlib.py
index 7083e9e..e1121a9 100644
--- a/Lib/test/test_pathlib.py
+++ b/Lib/test/test_pathlib.py
@@ -1878,6 +1878,21 @@ class DummyPathTest(unittest.TestCase):
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