I am very new to Python and am trying to get a response back from the URL for every user in the user.csv file, return the JSON message, then parse it to a CSV. I'm not sure what to put in the return section or how to split out the message. This is a sample of the message that is returned to me when I get the HTTP request:
{"msg": {"mes": "four", "high": 1230, "low": 0}}"
Here is what I have so far but I am getting an error:
TypeError: expected string or buffer
import requests
import json
import csv
def getRows(data):
return []
url = 'http://test_url'
with open('user.csv', 'rU') as data_file:
data = csv.DictReader(data_file)
for row in data:
current_user = row['mdn']
r = requests.get(url)
data = json.loads(data)
fname = "mydata.csv"
with open(fname,'wb') as outf:
outcsv = csv.writer(outf)
outcsv.writerows(getRows(data))
With the information you provide, you can do something like this:
import requests
import csv
url = 'http://test_url'
with open('user.csv', 'rU') as data_file:
data = csv.DictReader(data_file)
for row in data:
current_user = row['mdn']
r = requests.get(url) # probably you also need to send current_user somehow. "r = requests.get(url+'?user='+current_user)" maybe?
string_json = r.text.encode('utf-8')
json = eval(string_json) # only use this command if you are sure that string_json only contains a valid json and no malicious code instead
with open('outputfile.csv','a') as outfile:
outfile.write(current_user+';'+json["msg"]["mes"]+';'+json["msg"]["high"]+';'+json["msg"]["low"]+'\n')
Please provide more information about the HTTP request usage and about the format of your csv for a more precise answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.