Skip to content

Commit 6f4d068

Browse files
committed
Adding functionality for mode='a' when saving DataFrame.to_json. Only supported when lines=True and orient='records'.
1 parent 8f21b97 commit 6f4d068

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pandas/core/generic.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2400,6 +2400,7 @@ def to_json(
24002400
index: bool_t = True,
24012401
indent: int | None = None,
24022402
storage_options: StorageOptions = None,
2403+
mode: str = 'w',
24032404
) -> str | None:
24042405
"""
24052406
Convert the object to a JSON string.
@@ -2478,6 +2479,11 @@ def to_json(
24782479
24792480
.. versionadded:: 1.2.0
24802481
2482+
mode : str, default 'w' (writing)
2483+
Specify the IO mode for output when supplying a path_or_buf.
2484+
Accepted args are 'w' (writing) and 'a' (append) only.
2485+
Supplying mode='a' is only supported when lines is True and orient is 'records'.
2486+
24812487
Returns
24822488
-------
24832489
None or str
@@ -2661,6 +2667,7 @@ def to_json(
26612667
index=index,
26622668
indent=indent,
26632669
storage_options=storage_options,
2670+
mode=mode,
26642671
)
26652672

26662673
@final

pandas/io/json/_json.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ def to_json(
136136
index: bool = True,
137137
indent: int = 0,
138138
storage_options: StorageOptions = None,
139+
mode: str = 'w',
139140
) -> str | None:
140141

141142
if not index and orient not in ["split", "table"]:
@@ -146,6 +147,17 @@ def to_json(
146147
if lines and orient != "records":
147148
raise ValueError("'lines' keyword only valid when 'orient' is records")
148149

150+
if mode not in ['a', 'w']:
151+
raise ValueError(
152+
f"mode={mode!r} is not a valid option. Only 'w' and 'a' are currently supported."
153+
)
154+
155+
if mode == 'a' and (not lines or orient != 'records'):
156+
raise ValueError(
157+
"mode='a' (append) is only supported when lines is True and orient is 'records'"
158+
)
159+
160+
149161
if orient == "table" and isinstance(obj, Series):
150162
obj = obj.to_frame(name=obj.name or "values")
151163

@@ -177,7 +189,7 @@ def to_json(
177189
if path_or_buf is not None:
178190
# apply compression and byte/text conversion
179191
with get_handle(
180-
path_or_buf, "w", compression=compression, storage_options=storage_options
192+
path_or_buf, mode, compression=compression, storage_options=storage_options
181193
) as handles:
182194
handles.handle.write(s)
183195
else:

0 commit comments

Comments
 (0)