Commit 30985b2f authored by Karlind's avatar Karlind Committed by Kai Chen
Browse files

add support for pathlib to load and dump (#91)

* add support for pathlib to load and dump

* minor formatting
parent 5a5c94b6
from pathlib import Path
from ..utils import is_list_of, is_str from ..utils import is_list_of, is_str
from .handlers import BaseFileHandler, JsonHandler, PickleHandler, YamlHandler from .handlers import BaseFileHandler, JsonHandler, PickleHandler, YamlHandler
...@@ -16,7 +18,8 @@ def load(file, file_format=None, **kwargs): ...@@ -16,7 +18,8 @@ def load(file, file_format=None, **kwargs):
This method provides a unified api for loading data from serialized files. This method provides a unified api for loading data from serialized files.
Args: Args:
file (str or file-like object): Filename or a file-like object. file (str or :obj:`Path` or file-like object): Filename or a file-like
object.
file_format (str, optional): If not specified, the file format will be file_format (str, optional): If not specified, the file format will be
inferred from the file extension, otherwise use the specified one. inferred from the file extension, otherwise use the specified one.
Currently supported formats include "json", "yaml/yml" and Currently supported formats include "json", "yaml/yml" and
...@@ -25,6 +28,8 @@ def load(file, file_format=None, **kwargs): ...@@ -25,6 +28,8 @@ def load(file, file_format=None, **kwargs):
Returns: Returns:
The content from the file. The content from the file.
""" """
if isinstance(file, Path):
file = str(file)
if file_format is None and is_str(file): if file_format is None and is_str(file):
file_format = file.split('.')[-1] file_format = file.split('.')[-1]
if file_format not in file_handlers: if file_format not in file_handlers:
...@@ -48,14 +53,16 @@ def dump(obj, file=None, file_format=None, **kwargs): ...@@ -48,14 +53,16 @@ def dump(obj, file=None, file_format=None, **kwargs):
Args: Args:
obj (any): The python object to be dumped. obj (any): The python object to be dumped.
file (str or file-like object, optional): If not specified, then the file (str or :obj:`Path` or file-like object, optional): If not
object is dump to a str, otherwise to a file specified by the specified, then the object is dump to a str, otherwise to a file
filename or file-like object. specified by the filename or file-like object.
file_format (str, optional): Same as :func:`load`. file_format (str, optional): Same as :func:`load`.
Returns: Returns:
bool: True for success, False otherwise. bool: True for success, False otherwise.
""" """
if isinstance(file, Path):
file = str(file)
if file_format is None: if file_format is None:
if is_str(file): if is_str(file):
file_format = file.split('.')[-1] file_format = file.split('.')[-1]
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment