Home:ALL Converter>Using Python to Write JSON data in CSV file, and repeat multiple times

Using Python to Write JSON data in CSV file, and repeat multiple times

Ask Time:2017-01-28T12:15:00         Author:mmk88

Json Formatter

Trying to accomplish the following

  1. Every few seconds, have python pull unicode JSON data (THIS IS WORKING FINE)

  2. Save one item of that json data by, opening that CSV file on the desktop, clearing it, writing in it, and closing it (THIS IS THE ISSUE - CSV FILE STOPS UPDATING)

  3. Matlab will read the file process it (WORKS FINE)

  4. Go back to step 1

Way I am currently attempting it

MATLAB CODE:

system('python /weather.py');
load_weather_matlab();

if final_weather > 30
disp ('sunny')
else
disp ('not sunny')

PYTHON CODE:

r = requests.post(api_url + 'days', json=day, auth=auth)
print r.json()

r_output = r.json()
weather = r_output['weatherA']

print weather

with open(CSV_FILE, "w+") as fp:
    fp.close()

with open(CSV_FILE, "a") as fp:
    fp.write("%s" % (weather))
    fp.close()

MATLAB FUNCTION load_weather_matlab:

function [success] = load_weather_matlab();
global final_weather

 load_weather(); % Import the CSV File

      weather_temperature  = transpose(weather_temperature);
      final_weather = weather_temperature (1); 
success = 1;
end

MATLAB FUCTION load_weather:

filename = '/Users/m/Desktop/CSV_FILE';
delimiter = ',';
formatSpec = '%f[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'EmptyValue' ,NaN, 'ReturnOnError', false);
fclose(fileID);
weather_temperature = dataArray{:, 1};
clearvars filename delimiter formatSpec fileID dataArray ans;

THE ERROR I GET IS THAT 1) The file on the desktop CSV_FILE ... stops updating... 2) Sometimes if the JSON data being pulled by python does not have the 'weather' data then this is seen in MATLAB

Traceback (most recent call last):
  File "/Users/m/Desktop/weather.py", line 106, in <module>
    weather = r_output['weatherA']
KeyError: 'weatherA'

BUT OTHER TIMES (BEFORE IT STOPS UPDATING) it works.

This works for a couple of times, but then it stops. I am not sure why ? Sometimes, I get a KeyError when the 'weather' is not in the JSON, but this shouldn't just stop the file from updating correct?

any help appreciated

thanks

Author:mmk88,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41906259/using-python-to-write-json-data-in-csv-file-and-repeat-multiple-times
yy