title: How to append new row to csv file with pandas?
body: <p>I want to save data that I received from mosquitto broker as csv file. Below are the script for <code>mqtt_subscribe.py</code></p>
  
  <pre><code>import paho.mqtt.client as mqtt
  import pandas as pd
  
  def on_connect(client, userdata, rc):
      print("Connected with result code "+str(rc))
      client.subscribe("test")
  
  def on_message(client, userdata, msg):
      print str(msg.payload)
      datas = map(int, msg.payload)
      df = pd.DataFrame(data=datas, columns=['numbers'])
  
      f = open("test.csv", 'a')
      df.to_csv(f)
      f.close()
  
  client = mqtt.Client()
  client.on_connect = on_connect
  client.on_message = on_message
  
  client.connect("localhost", 1883, 60)
  
  client.loop_forever()
  </code></pre>
  
  <p>This script will print random number/data received from the broker (until I manually stop the script) like this(Example)</p>
  
  <pre><code>Connected with result code 0
  4
  7
  7
  </code></pre>
  
  <p>I am hoping to write this result in CSV file like this</p>
  
  <pre><code>,numbers
  0,4
  1,7
  2,7
  </code></pre>
  
  <p>but instead I got this</p>
  
  <pre><code>,numbers
  0,4
  ,numbers
  0,7
  ,numbers
  0,7
  </code></pre>
  
  <p>Am I missing something here? I believe it is because method <code>on_message</code> keep overwriting the dataframe with the column but I do not know where should I initialize the dataframe other than inside <code>on_message</code> method.</p>
  
  <p>Thank you in advance.</p>