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.
This commit is contained in:
Georg Brandl 2014-10-01 19:12:33 +02:00
parent 5c4725e5bc
commit ea68398355
4 changed files with 114 additions and 0 deletions

View file

@ -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.