Dump data to json/yaml strings or files. This method provides a unified api for dumping data as strings or to files. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is du
(obj, file=None, file_format=None, **kwargs)
| 57 | |
| 58 | |
| 59 | def dump(obj, file=None, file_format=None, **kwargs): |
| 60 | """Dump data to json/yaml strings or files. |
| 61 | |
| 62 | This method provides a unified api for dumping data as strings or to files. |
| 63 | |
| 64 | Args: |
| 65 | obj (any): The python object to be dumped. |
| 66 | file (str or :obj:`Path` or file-like object, optional): If not |
| 67 | specified, then the object is dumped to a str, otherwise to a file |
| 68 | specified by the filename or file-like object. |
| 69 | file_format (str, optional): Same as :func:`load`. |
| 70 | |
| 71 | Examples: |
| 72 | >>> dump('hello world', '/path/of/your/file') # disk |
| 73 | >>> dump('hello world', 'oss://path/of/your/file') # oss |
| 74 | |
| 75 | Returns: |
| 76 | bool: True for success, False otherwise. |
| 77 | """ |
| 78 | if isinstance(file, Path): |
| 79 | file = str(file) |
| 80 | if file_format is None: |
| 81 | if isinstance(file, str): |
| 82 | file_format = file.split('.')[-1] |
| 83 | elif file is None: |
| 84 | raise ValueError( |
| 85 | 'file_format must be specified since file is None') |
| 86 | if file_format not in format_handlers: |
| 87 | raise TypeError(f'Unsupported format: {file_format}') |
| 88 | |
| 89 | handler = format_handlers[file_format] |
| 90 | if file is None: |
| 91 | return handler.dump_to_str(obj, **kwargs) |
| 92 | elif isinstance(file, str): |
| 93 | if handler.text_mode: |
| 94 | with StringIO() as f: |
| 95 | handler.dump(obj, f, **kwargs) |
| 96 | File.write_text(f.getvalue(), file) |
| 97 | else: |
| 98 | with BytesIO() as f: |
| 99 | handler.dump(obj, f, **kwargs) |
| 100 | File.write(f.getvalue(), file) |
| 101 | elif hasattr(file, 'write'): |
| 102 | handler.dump(obj, file, **kwargs) |
| 103 | else: |
| 104 | raise TypeError('"file" must be a filename str or a file-object') |
| 105 | |
| 106 | |
| 107 | def dumps(obj, format, **kwargs): |
searching dependent graphs…