I'm using Requests to upload a PDF to an API. It is stored as "response" below. I'm trying to write that out to Excel.
import requests files = {'f': ('1.pdf', open('1.pdf', 'rb'))} response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files) response.raise_for_status() # ensure we notice bad responses file = open("out.xls", "w") file.write(response) file.close()
I'm getting the error:
file.write(response) TypeError: expected a character buffer object
What can Requests do? Requests will allow you to send HTTP/1.1 requests using Python. With it, you can add content like headers, form data, multipart files, and parameters via simple Python libraries. It also allows you to access the response data of Python in the same way.
I believe all the existing answers contain the relevant information, but I would like to summarize.
The response object that is returned by requests
get and post operations contains two useful attributes:
response.text
- Contains str
with the response text.response.content
- Contains bytes
with the raw response content.You should choose one or other of these attributes depending on the type of response you expect.
response.text
response.content
.When writing responses to file you need to use the open function with the appropriate file write mode.
"w"
- plain write mode."wb"
- binary write mode.# Request the HTML for this web page: response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file") with open("response.txt", "w") as f: f.write(response.text)
# Request the profile picture of the OP: response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1") with open("response.jpg", "wb") as f: f.write(response.content)
The original code should work by using wb
and response.content
:
import requests files = {'f': ('1.pdf', open('1.pdf', 'rb'))} response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files) response.raise_for_status() # ensure we notice bad responses file = open("out.xls", "wb") file.write(response.content) file.close()
But I would go further and use the with
context manager for open
.
import requests with open('1.pdf', 'rb') as file: files = {'f': ('1.pdf', file)} response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files) response.raise_for_status() # ensure we notice bad responses with open("out.xls", "wb") as file: file.write(response.content)
You can use the response.text
to write to a file:
import requests files = {'f': ('1.pdf', open('1.pdf', 'rb'))} response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files) response.raise_for_status() # ensure we notice bad responses with open("resp_text.txt", "w") as file: file.write(response.text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With