Tags
python
Asked 3 years ago
12 Aug 2021
Views 5288
Oral

Oral posted

Python - TypeError: write() argument must be str, not dict

TypeError: write() argument must be str, not dict in python


import requests
r=requests.get(url)
filename='news.json'
file = open(filename, 'w')
file.write(str(r))
file.close()


at above code instead of making file of the json , Python making empty file and throw this errror
TypeError: write() argument must be str, not dict
dilip

dilip
answered Aug 12 '21 00:00

try this requests.models.Response.content

so here requests.get() will return requests.models.Response object , and you cant cast to string directly
use requests.models.Response.content , in our case response.content and convert to string by str() function so it become str(response.content )

following working python code to make json file from live api call by requests :



import requests
response=requests.get(url)
filename='news.json'
file = open(filename, 'w')
file.write(str(response.content))
file.close()
no this does not work actually, it save file but it don't open again as JSON file , I checked with JSON viewer - Oral  
Aug 12 '21 14:57
Post Answer