0

I have a list of data which is then converted into pandas Data Frame and added to csv file. The only problem is that I cannot find a way to name columns in that csv. Here is a piece of code that loads the data into a .csv

def on_message(ws, message):
    print('Otrzymano wiadomość')
    print(message)
    json_message = json.loads(message)#Decoding json
    price_data = [json_message["data"]["o"]]
    price_data.append(json_message["data"]["c"])
    price_data.append(json_message["data"]["h"])
    price_data.append(json_message["data"]["l"])
    time_stamp = dt.datetime.now()
    time_stamp = time_stamp.strftime('%Y-%m-%d %H:%M:%S')
    col = [time_stamp]
    col.extend(price_data)
    df = pd.DataFrame(col)
    df = df.T
    df.to_csv(str(time_stamp[0:11]) + 'stockdata.csv', mode = 'a', header = False)
    print(df)
  • Does this answer your question? [Pythonically add header to a csv file](https://stackoverflow.com/questions/20347766/pythonically-add-header-to-a-csv-file) – René Höhle Aug 14 '21 at 08:55

1 Answers1

0

Change the line before print(df) to:

df.columns = ['your', 'column', 'names']
df.to_csv(str(time_stamp[0:11]) + 'stockdata.csv')

I see you had the mode='a' flag. Are you creating new files or appending to existing ones? In the latter case, keep your code as it is but first thing in your program initiate the header with:

with open('YOURFILENAME', 'w') as f:
    f.write('your,column,names\n')
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Thank you very much for your answer. This is a block of code that has a command run_forever, so the first time through it creates a file and then adds new lines to already created csv. I think this complicates matter a little bit – Dominik Pucuła Aug 14 '21 at 09:22
  • No it's simple. Just initiate your file with the header the first time, see the second part of my answer. – mozway Aug 14 '21 at 09:25