# HG changeset patch # User Ram Rachum # Date 1390391098 -7200 # Node ID a7827efc4273c53d756553e466c086f11bc8c99e # Parent 9bbb64e91913dc80b6340ff1647ec54905830dc5 Add read, write, readlines and writelines to Path diff -r 9bbb64e91913 -r a7827efc4273 Lib/pathlib.py --- a/Lib/pathlib.py Wed Jan 22 03:05:49 2014 -0800 +++ b/Lib/pathlib.py Wed Jan 22 13:44:58 2014 +0200 @@ -1069,6 +1069,50 @@ return io.open(str(self), mode, buffering, encoding, errors, newline, opener=self._opener) + def read(self, size=None, mode='r', buffering=-1, encoding=None, + errors=None, newline=None): + '''Open the file, read it, and close the file.''' + if 'r' not in mode: + raise Exception('Mode for `Path.read` must contain `r`.') + with self.open(mode=mode, buffering=buffering, encoding=encoding, + errors=errors, newline=newline) as file: + return file.read(size) + + def readlines(self, mode='r', buffering=-1, encoding=None, + errors=None, newline=None): + ''' + Open the file, read it, and close the file. Returns output in lines. + ''' + if 'r' not in mode: + raise Exception('Mode for `Path.readlines` must contain `r`.') + with self.open(mode=mode, buffering=buffering, encoding=encoding, + errors=errors, newline=newline) as file: + return file.readlines() + + def write(self, data, mode='w', buffering=-1, encoding=None, + errors=None, newline=None): + '''Open the file, write to it, and close the file.''' + if not {'w', 'a', 'x'} & set(mode): + raise Exception( + 'Mode for `Path.write` must contain `w`, `a` or `x`.' + ) + with self.open(mode=mode, buffering=buffering, encoding=encoding, + errors=errors, newline=newline) as file: + return file.write(data) + + def writelines(self, data, mode='w', buffering=-1, encoding=None, + errors=None, newline=None): + ''' + Open the file, write to it, and close the file. Takes input as lines. + ''' + if not {'w', 'a', 'x'} & set(mode): + raise Exception( + 'Mode for `Path.writelines` must contain `w`, `a` or `x`.' + ) + with self.open(mode=mode, buffering=buffering, encoding=encoding, + errors=errors, newline=newline) as file: + return file.writelines(data) + def touch(self, mode=0o666, exist_ok=True): """ Create this file with the given access mode, if it doesn't exist.