From 8ac7988dee11745495290f38fa5a2b8fddd0b993 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Jan 2024 14:33:17 -0500 Subject: [PATCH] chore: add write_to_file binary helper method (#309) --- src/anthropic/_legacy_response.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/anthropic/_legacy_response.py b/src/anthropic/_legacy_response.py index b2831394..483170a8 100644 --- a/src/anthropic/_legacy_response.py +++ b/src/anthropic/_legacy_response.py @@ -336,6 +336,22 @@ def iter_lines(self) -> Iterator[str]: def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]: return self.response.iter_raw(chunk_size) + def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')` + """ + with open(file, mode="wb") as f: + for data in self.response.iter_bytes(): + f.write(data) + @deprecated( "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead" )