1+ # Copyright 2009-2014 Ram Rachum.
2+ # This program is distributed under the MIT license.
3+
4+ from python_toolbox import monkeypatching_tools
5+
6+ try :
7+ import pathlib
8+
9+ except ImportError :
10+ pass
11+
12+ else :
13+
14+ @monkeypatching_tools .monkeypatch (pathlib .Path , override_if_exists = False )
15+ def read_bytes (self ):
16+ """
17+ Open the file in bytes mode, read it, and close the file.
18+ """
19+ with self .open (mode = 'rb' ) as f :
20+ return f .read ()
21+
22+ @monkeypatching_tools .monkeypatch (pathlib .Path , override_if_exists = False )
23+ def read_text (self , encoding = None , errors = None , newline = None ):
24+ """
25+ Open the file in text mode, read it, and close the file.
26+ """
27+ with self .open (mode = 'r' , encoding = encoding ,
28+ errors = errors , newline = newline ) as f :
29+ return f .read ()
30+
31+ @monkeypatching_tools .monkeypatch (pathlib .Path , override_if_exists = False )
32+ def write_bytes (self , data , append = False , exclusive = False ):
33+ """
34+ Open the file in bytes mode, write to it, and close the file.
35+ """
36+ if append and exclusive :
37+ raise TypeError ('write_bytes does not accept both '
38+ '"append" and "exclusive" mode.' )
39+ mode = 'ab' if append else 'xb' if exclusive else 'wb'
40+ with self .open (mode = mode ) as f :
41+ return f .write (data )
42+
43+ @monkeypatching_tools .monkeypatch (pathlib .Path , override_if_exists = False )
44+ def write_text (self , data , encoding = None , errors = None ,
45+ newline = None , append = False , exclusive = False ):
46+ """
47+ Open the file in text mode, write to it, and close the file.
48+ """
49+ if append and exclusive :
50+ raise TypeError ('write_text does not accept both '
51+ '"append" and "exclusive" mode.' )
52+ mode = 'a' if append else 'x' if exclusive else 'w'
53+ with self .open (mode = mode , encoding = encoding ,
54+ errors = errors , newline = newline ) as f :
55+ return f .write (data )
56+
0 commit comments