Skip to content

Commit dfd0d25

Browse files
committed
-
1 parent 4e2bcfe commit dfd0d25

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

source_py3/python_toolbox/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import python_toolbox.version_info
1616
import python_toolbox.monkeypatch_copyreg
1717
import python_toolbox.monkeypatch_envelopes
18+
import python_toolbox.monkeypatch_pathlib
1819

1920
__version_info__ = python_toolbox.version_info.VersionInfo(0, 6, 7)
2021
__version__ = __version_info__.version_text
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)