summaryrefslogtreecommitdiffstats
path: root/Lib/pathlib.py
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2014-10-01 17:12:33 (GMT)
committerGeorg Brandl <georg@python.org>2014-10-01 17:12:33 (GMT)
commitea6839835557784433669a43c763c296ce9afd21 (patch)
treee2fe412eb90b05e915de41ae6c6aecbab2e6870d /Lib/pathlib.py
parent5c4725e5bc4c25ff3f9771bf8985bcb52fea23e7 (diff)
downloadcpython-ea6839835557784433669a43c763c296ce9afd21.zip
cpython-ea6839835557784433669a43c763c296ce9afd21.tar.gz
cpython-ea6839835557784433669a43c763c296ce9afd21.tar.bz2
Closes #20218: Added convenience methods read_text/write_text and read_bytes/
write_bytes to pathlib.Path objects. Thanks to Christopher Welborn and Ram Rachum for original patches.
Diffstat (limited to 'Lib/pathlib.py')
-rw-r--r--Lib/pathlib.py33
1 files changed, 33 insertions, 0 deletions
diff --git a/Lib/pathlib.py b/Lib/pathlib.py
index eff6ae3..5134eea 100644
--- a/Lib/pathlib.py
+++ b/Lib/pathlib.py
@@ -1083,6 +1083,39 @@ class Path(PurePath):
return io.open(str(self), mode, buffering, encoding, errors, newline,
opener=self._opener)
+ def read_bytes(self):
+ """
+ Open the file in bytes mode, read it, and close the file.
+ """
+ with self.open(mode='rb') as f:
+ return f.read()
+
+ def read_text(self, encoding=None, errors=None):
+ """
+ Open the file in text mode, read it, and close the file.
+ """
+ with self.open(mode='r', encoding=encoding, errors=errors) as f:
+ return f.read()
+
+ def write_bytes(self, data):
+ """
+ Open the file in bytes mode, write to it, and close the file.
+ """
+ # type-check for the buffer interface before truncating the file
+ view = memoryview(data)
+ with self.open(mode='wb') as f:
+ return f.write(view)
+
+ def write_text(self, data, encoding=None, errors=None):
+ """
+ Open the file in text mode, write to it, and close the file.
+ """
+ if not isinstance(data, str):
+ raise TypeError('data must be str, not %s' %
+ data.__class__.__name__)
+ with self.open(mode='w', encoding=encoding, errors=errors) as f:
+ return f.write(data)
+
def touch(self, mode=0o666, exist_ok=True):
"""
Create this file with the given access mode, if it doesn't exist.