added capability to handle Path/LocalPath objects · pandas-dev/pandas@0d3dcbb (original) (raw)
`@@ -5,10 +5,24 @@
`
5
5
`import zipfile
`
6
6
`from contextlib import contextmanager, closing
`
7
7
``
8
``
`-
from pandas.compat import StringIO, string_types, BytesIO
`
``
8
`+
from pandas.compat import StringIO, BytesIO, string_types, text_type
`
9
9
`from pandas import compat
`
10
10
``
11
11
``
``
12
`+
try:
`
``
13
`+
import pathlib
`
``
14
`+
_PATHLIB_INSTALLED = True
`
``
15
`+
except ImportError:
`
``
16
`+
_PATHLIB_INSTALLED = False
`
``
17
+
``
18
+
``
19
`+
try:
`
``
20
`+
from py.path import local as LocalPath
`
``
21
`+
_PY_PATH_INSTALLED = True
`
``
22
`+
except:
`
``
23
`+
_PY_PATH_INSTALLED = False
`
``
24
+
``
25
+
12
26
`if compat.PY3:
`
13
27
`from urllib.request import urlopen, pathname2url
`
14
28
`_urlopen = urlopen
`
`@@ -201,6 +215,25 @@ def _validate_header_arg(header):
`
201
215
`"header=int or list-like of ints to specify "
`
202
216
`"the row(s) making up the column names")
`
203
217
``
``
218
`+
def _stringify_path(filepath_or_buffer):
`
``
219
`+
"""Return the argument coerced to a string if it was a pathlib.Path
`
``
220
`+
or a py.path.local
`
``
221
+
``
222
`+
Parameters
`
``
223
`+
`
``
224
`+
filepath_or_buffer : object to be converted
`
``
225
+
``
226
`+
Returns
`
``
227
`+
`
``
228
`+
str_filepath_or_buffer : a the string version of the input path
`
``
229
`+
"""
`
``
230
`+
if _PATHLIB_INSTALLED and isinstance(filepath_or_buffer, pathlib.Path):
`
``
231
`+
return text_type(filepath_or_buffer)
`
``
232
`+
if _PY_PATH_INSTALLED and isinstance(filepath_or_buffer, LocalPath):
`
``
233
`+
return filepath_or_buffer.strpath
`
``
234
`+
return filepath_or_buffer
`
``
235
+
``
236
+
204
237
`def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
`
205
238
`compression=None):
`
206
239
`"""
`
`@@ -209,7 +242,8 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
`
209
242
``
210
243
` Parameters
`
211
244
` ----------
`
212
``
`-
filepath_or_buffer : a url, filepath, or buffer
`
``
245
`+
filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),
`
``
246
`+
or buffer
`
213
247
` encoding : the encoding to use to decode py3 bytes, default is 'utf-8'
`
214
248
``
215
249
` Returns
`
`@@ -257,6 +291,8 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
`
257
291
`filepath_or_buffer = k
`
258
292
`return filepath_or_buffer, None, compression
`
259
293
``
``
294
`+
It is a pathlib.Path/py.path.local or string
`
``
295
`+
filepath_or_buffer = _stringify_path(filepath_or_buffer)
`
260
296
`return _expand_user(filepath_or_buffer), None, compression
`
261
297
``
262
298
``