使用Python在CSV文件中写入JSON数据,并重复多次

使用Python在CSV文件中写入JSON数据,并重复多次,python,json,matlab,csv,Python,Json,Matlab,Csv,尝试完成以下任务 每隔几秒钟,让python提取unicode JSON数据(这很好) 保存一项json数据,方法是:在桌面上打开CSV文件,清除它,写入它,然后关闭它(这就是问题所在-CSV文件停止更新) Matlab会读取文件的过程吧(工作很好) 返回到步骤1 我现在尝试的方式 MATLAB代码: system('python /weather.py'); load_weather_matlab(); if final_weather > 30 disp ('sunny') else

尝试完成以下任务

  • 每隔几秒钟,让python提取unicode JSON数据(这很好)

  • 保存一项json数据,方法是:在桌面上打开CSV文件,清除它,写入它,然后关闭它(这就是问题所在-CSV文件停止更新)

  • Matlab会读取文件的过程吧(工作很好)

  • 返回到步骤1

  • 我现在尝试的方式

    MATLAB代码:

    system('python /weather.py');
    load_weather_matlab();
    
    if final_weather > 30
    disp ('sunny')
    else
    disp ('not sunny')
    
    PYTHON代码:

    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函数加载\u天气\u 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功能负载\天气:

    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;
    
    我得到的错误是 1)桌面CSV\u文件上的文件。。。停止更新… 2) 有时,如果python提取的JSON数据没有“天气”数据 然后在MATLAB中可以看到这一点

    Traceback (most recent call last):
      File "/Users/m/Desktop/weather.py", line 106, in <module>
        weather = r_output['weatherA']
    KeyError: 'weatherA'
    
    回溯(最近一次呼叫最后一次):
    文件“/Users/m/Desktop/weather.py”,第106行,在
    weather=r_输出['weatherA']
    KeyError:'weatherA'
    
    但其他时候(在它停止更新之前)它是有效的

    这可以工作几次,但之后就停止了。我不知道为什么?有时,当JSON中没有“weather”时,我会收到一个keyrerror,但这不应该只是阻止文件更新正确吗

    谢谢你的帮助


    谢谢

    看起来您的JSON文件没有
    'weatherA'
    键。是的,这确实停止了整个脚本。因此,在请求字典中的
    'weatherA'
    之前,请确保它存在:
    如果r\u输出中的'weatherA':…
    作为旁注:您只需要
    打开(CSV\u文件,“w”)作为fp:fp.write(weather)
    。所有其他与文件相关的行都是不必要的。而且当您将
    一起使用时,您不会关闭
    fp
    ,它会处理它。