-1

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 !

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It would be simpler to just move the open out of the loop and use a with statement to ensure the file gets closed.
Oh, I totally agree. I wanted to give an answer that changed as little as possible, but a better solution would be something like you described.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.