Search code examples
pythonwindowsserial-portwritefile

write on file from serial in python in windows


I trying to have a very simple script to read data from serial port and write it on a txt file. My data are always the same and for example look like this : '4\r\n'

import serial
import time
ser = serial.Serial('COM5', 9600, timeout=0) 

while 1:
   data=ser.readline()
   print data
   f = open('myfile.txt','w') 
   data=str(data)
   f.write(data)
   f.close()
   time.sleep(1) 

I am using python2.7 on windows 7 my print work fine I get the data, but I couldn't write on file...

thanks a lot !


Solution

  • Using the 'w' option in open() tells python to delete your file first, then open it. Try changing the 'w' to an 'a' so that Python appends new data to the end of the file, rather than deleting the file every time.

    f = open('myfile.txt', 'a')
    

    You can read more about the open function here. Specifically, check out the documentation for the mode argument.