Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: 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
(file, file_format=None, **kwargs)
| 15 | |
| 16 | |
| 17 | def load(file, file_format=None, **kwargs): |
| 18 | """Load data from json/yaml/pickle files. |
| 19 | |
| 20 | This method provides a unified api for loading data from serialized files. |
| 21 | |
| 22 | Args: |
| 23 | file (str or :obj:`Path` or file-like object): Filename or a file-like |
| 24 | object. |
| 25 | file_format (str, optional): If not specified, the file format will be |
| 26 | inferred from the file extension, otherwise use the specified one. |
| 27 | Currently supported formats include "json", "yaml/yml". |
| 28 | |
| 29 | Examples: |
| 30 | >>> load('/path/of/your/file') # file is stored in disk |
| 31 | >>> load('https://path/of/your/file') # file is stored on internet |
| 32 | >>> load('oss://path/of/your/file') # file is stored in petrel |
| 33 | |
| 34 | Returns: |
| 35 | The content from the file. |
| 36 | """ |
| 37 | if isinstance(file, Path): |
| 38 | file = str(file) |
| 39 | if file_format is None and isinstance(file, str): |
| 40 | file_format = file.split('.')[-1] |
| 41 | if file_format not in format_handlers: |
| 42 | raise TypeError(f'Unsupported format: {file_format}') |
| 43 | |
| 44 | handler = format_handlers[file_format] |
| 45 | if isinstance(file, str): |
| 46 | if handler.text_mode: |
| 47 | with StringIO(File.read_text(file)) as f: |
| 48 | obj = handler.load(f, **kwargs) |
| 49 | else: |
| 50 | with BytesIO(File.read(file)) as f: |
| 51 | obj = handler.load(f, **kwargs) |
| 52 | elif hasattr(file, 'read'): |
| 53 | obj = handler.load(file, **kwargs) |
| 54 | else: |
| 55 | raise TypeError('"file" must be a filepath str or a file-object') |
| 56 | return obj |
| 57 | |
| 58 | |
| 59 | def dump(obj, file=None, file_format=None, **kwargs): |
searching dependent graphs…