diff -r 0056aaf42bf7 Lib/pathlib.py --- a/Lib/pathlib.py Wed Jan 15 15:09:43 2014 +0000 +++ b/Lib/pathlib.py Thu Jan 23 18:36:55 2014 -0600 @@ -1069,6 +1069,39 @@ 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, newline=None): + """ + Open the file in text mode, read it, and close the file. + """ + with self.open(mode='r', encoding=encoding, + errors=errors, newline=newline) as f: + return f.read() + + def write_bytes(self, data, append=False): + """ + Open the file in bytes mode, write to it, and close the file. + """ + mode = 'ab' if append else 'wb' + with self.open(mode=mode) as f: + return f.write(data) + + def write_text(self, data, + encoding=None, errors=None, newline=None, append=False): + """ + Open the file in text mode, write to it, and close the file. + """ + mode = 'a' if append else 'w' + with self.open(mode=mode, encoding=encoding, + errors=errors, newline=newline) 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. diff -r 0056aaf42bf7 Lib/test/test_pathlib.py --- a/Lib/test/test_pathlib.py Wed Jan 15 15:09:43 2014 +0000 +++ b/Lib/test/test_pathlib.py Thu Jan 23 18:36:55 2014 -0600 @@ -1250,6 +1250,41 @@ self.assertIsInstance(f, io.RawIOBase) self.assertEqual(f.read().strip(), b"this is file A") + def test_read_bytes(self): + p = self.cls(BASE) + with (p / 'fileA').open('wb') as f: + f.write(b'abcdef') + f.flush() + self.assertEqual((p / 'fileA').read_bytes(), b'abcdef') + + def test_read_text(self): + p = self.cls(BASE) + with (p / 'fileA').open('w') as f: + f.write('abcdef') + f.flush() + self.assertEqual((p / 'fileA').read_text(), 'abcdef') + + def test_write_bytes(self): + p = self.cls(BASE) + (p / 'fileA').write_bytes(b'abcdefg') + with (p / 'fileA').open('rb') as f: + self.assertEqual(f.read(), b'abcdefg') + (p / 'fileA').write_bytes(b'hijk', append=True) + with (p / 'fileA').open('rb') as f: + self.assertEqual(f.read(), b'abcdefghijk') + self.assertRaises(TypeError, (p / 'fileA').write_bytes, 'badstr') + + def test_write_text(self): + p = self.cls(BASE) + (p / 'fileA').write_text('abcdefg') + with (p / 'fileA').open('r') as f: + self.assertEqual(f.read(), 'abcdefg') + (p / 'fileA').write_text('hijk', append=True) + with (p / 'fileA').open('r') as f: + self.assertEqual(f.read(), 'abcdefghijk') + + self.assertRaises(TypeError, (p / 'fileA').write_text, b'badbytes') + def test_iterdir(self): P = self.cls p = P(BASE)