diff --git a/pandas/core/generic.py b/pandas/core/generic.py index fe412bc0ce937..c3c4a14146541 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2063,6 +2063,7 @@ def to_json( index: bool_t = True, indent: Optional[int] = None, storage_options: StorageOptions = None, + mode: str = "w", ) -> Optional[str]: """ Convert the object to a JSON string. @@ -2156,6 +2157,13 @@ def to_json( .. versionadded:: 1.2.0 + mode : str, default 'w' + If 'orient' is 'records' and 'lines' is 'True' enable option to append + mode ('mode' is 'a') to a json file instead of overwriting. + Will throw ValueError if incorrect 'orient' and 'lines'. + + .. versionadded:: 1.2.0 + Returns ------- None or str @@ -2335,6 +2343,7 @@ def to_json( index=index, indent=indent, storage_options=storage_options, + mode=mode, ) def to_hdf( diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index fe5e172655ae1..627b8a48100a8 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -50,6 +50,7 @@ def to_json( index: bool = True, indent: int = 0, storage_options: StorageOptions = None, + mode: str = "w", ): if not index and orient not in ["split", "table"]: @@ -68,6 +69,11 @@ def to_json( if lines and orient != "records": raise ValueError("'lines' keyword only valid when 'orient' is records") + if mode == "a" and (not lines or orient != "records"): + raise ValueError( + "'append mode' only valid when 'line' is True and 'orient' is records" + ) + if orient == "table" and isinstance(obj, Series): obj = obj.to_frame(name=obj.name or "values") @@ -95,9 +101,19 @@ def to_json( if lines: s = convert_to_line_delimits(s) + try: + add_new_line = ( + mode == "a" + and os.path.exists(path_or_buf) + and os.path.isfile(path_or_buf) + and os.path.getsize(path_or_buf) + ) + s = "\n" + s if add_new_line else s + except (TypeError, ValueError): + pass if isinstance(path_or_buf, str): - fh, handles = get_handle(path_or_buf, "w", compression=compression) + fh, handles = get_handle(path_or_buf, mode, compression=compression) try: fh.write(s) finally: