Нужно записывать данные из websocket в csv
Через csv.writer() записывает в таком виде:
{,"""",e,"""",:,"""",t,r,a,d,e,"""",",","""",E,"""",:,1,5,8,7,8,1,5,9,0,2,8,2,5,",","""",s,"""",:,"""",E,T,H,B,T,C,"""",",","""",t,"""",:,1,7,3,3,3,0,8,2,3,",","""",p,"""",:,"""",0,.,0,2,5,6,7,9,0,0,"""",",","""",q,"""",:,"""",0,.,0,0,6,0,0,0,0,0,"""",",","""",b,"""",:,6,9,6,4,2,6,6,5,9,",","""",a,"""",:,6,9,6,4,2,5,9,0,6,",","""",T,"""",:,1,5,8,7,8,1,5,9,0,2,8,2,4,",","""",m,"""",:,f,a,l,s,e,",","""",M,"""",:,t,r,u,e,}
А нужно в таком:
{"e":"trade","E":1587829646075,"s":"ETHBTC","t":173345011,"p":"0.02580800","q":"0.25500000","b":696586264,"a":696586267,"T":1587829646073,"m":true,"M":true}
Через csv.DictWriter() записывает хэдэр, но строчки не пишет... Что не так?
import websocket, csv
fieldname = ['e', 'E', 's', 't', 'p', 'q', 'b', 'a', 'T', 'm', 'M']
with open('Binance_websoket.csv', 'a', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fieldname)
writer.writeheader()
def on_message(ws, message):
print(message)
writer.writerow(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
print("### connected ###")
if __name__ == "__main__":
ws = websocket.WebSocketApp("wss://stream.binance.com:9443/ws/ltcbtc@aggTrade/ethbtc@trade",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()