Skip to content

Commit

Permalink
Support opening pathlib.Path
Browse files Browse the repository at this point in the history
  • Loading branch information
clintval committed Mar 14, 2018
1 parent ecb24c2 commit b9d4d76
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions smart_open/smart_open_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ def smart_open(uri, mode="rb", **kw):
3. a URI for Amazon's S3 (can also supply credentials inside the URI):
`s3://my_bucket/lines.txt`, `s3://my_aws_key_id:key_secret@my_bucket/lines.txt`
4. an instance of the boto.s3.key.Key class.
5. an instance of the pathlib.Path class.
Examples::
Expand Down Expand Up @@ -163,6 +164,14 @@ def smart_open(uri, mode="rb", **kw):
if not isinstance(mode, six.string_types):
raise TypeError('mode should be a string')

# Support opening ``pathlib.Path`` objects by casting them to strings.
try:
from pathlib import Path
if isinstance(uri, Path):
uri = str(uri)
except ImportError:
pass

if isinstance(uri, six.string_types):
# this method just routes the request to classes handling the specific storage
# schemes, depending on the URI protocol in `uri`
Expand Down
10 changes: 10 additions & 0 deletions smart_open/tests/test_smart_open.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,16 @@ def test_open_with_keywords_explicit_r(self):
actual = fin.read()
self.assertEqual(expected, actual)

def test_open_pathlib_path(self):
"""If ``pathlib.Path`` is available we should open it."""
try:
from pathlib import Path
fpath = Path(os.path.join(CURR_DIR, 'test_data/cp852.tsv.txt'))
with open(fpath, 'rb') as fin:
fin.read().decode('cp852')
except ImportError:
pass

@mock_s3
def test_read_never_returns_none(self):
"""read should never return None."""
Expand Down

0 comments on commit b9d4d76

Please sign in to comment.