title: Clear serial buffer before acquiring data
body: <p>I've created a short script in python which reads incoming serial data from an Arduino and writes it to a CSV file. I've created headers (data labels) in the Arduino program which are passed as the first string values and assigned as the column headers. However, for some reason the data headers are preceded by a small collection of data which I assume is old data in the USB serial buffer. Is there anyway I can tell python to wait until the old data is cleared and the Arduino has reset the serial connection?</p>
  <p>Code is shown below, any help would be appreciated.</p>
  <p><a href="https://i.stack.imgur.com/dyPs3.png" rel="nofollow noreferrer">Snapshot of issue</a></p>
  <pre><code>import serial
  from datetime import datetime
  import time
  import pandas as pd
  import random
  
  a = input(&quot;Enter a:&quot;)
  b = input(&quot;Enter b:&quot;)
  c = input(&quot;Enter c:&quot;)
  d = input(&quot;Enter d:&quot;)
  
  fileName= a + &quot;-&quot; + b + &quot;-&quot; + c + &quot;-&quot; + d + &quot;.csv&quot; #name of the CSV file generated
  arduino_port = &quot;COM7&quot;
  baud = 115200
  print_labels = False
  
  file = open(fileName, &quot;w&quot;, newline=&quot;&quot;)
  print(&quot;Created file&quot;)
  
  ser = serial.Serial(arduino_port, baud)
  print(&quot;Connected to Arduino port:&quot; + arduino_port)
  
  line = 0 #start at 0 because our header is 0 (not real data)
  
  while True:
      
      getData = (ser.readline().decode())
      data=getData[0:][:-1]
      now = datetime.now()
      dt_string = now.strftime(&quot;%d/%m/%Y %H:%M:%S&quot;)
  
      time.sleep(1)
  
      if data
      
      if line == 0:
          print(data)
          file = open(fileName, &quot;a&quot;, newline=&quot;&quot;)
          file.write(data + &quot;\n&quot;) #write data with a newline
          line = line+1
      else:
          print(data + &quot;,&quot; + dt_string)
          file = open(fileName, &quot;a&quot;, newline=&quot;&quot;)
          file.write(data + &quot;,&quot; + dt_string + &quot;\n&quot;) #write data with a newline
          line = line+1
  
  print(&quot;Data collection complete!&quot;)
  file.close()
  </code></pre>