0

I am able to read GPS data through gpsd and gps pipe. But when I try to read GPS data in python code and write to a file in the same code. The file remains empty

import serial
import time
ser = serial.Serial('/dev/ttyS0')
f=open("myFile.txt","w+")
while 1:
        x=ser.readline()
        print (x)
        f.write('writing to a file \n')

GPS data is displayed correctly and myFile.txt is created. But when I open it is blank. Can anyone help me on this?

Note: I have tried this while using reading other devices through the USB-port and it works just fine

0

Please flush after using. Add f.flush() after your write, or open your file with a zero buffering size.

1

The data is held in a memory buffer because memory is faster than disk i/o. Your data would be written to the file once you close the file, but I guess you want to read it wile you're writing it? To do that, the f.flush() suggested by @Gerard will cause the memory buffer to be written to your file; or at least to the system's disk cache if it's using one. You may also wish to consider adding an os.fsync(f) following the f.flush. This will ensure that the system's disk cache is also written to the file, and avoid data loss in the event of an "unexpected event".

As a general practice, I think I would avoid using a zero-sized buffer for your file. That would defeat the purpose of using memory buffers, which is to keep things moving briskly forward. But feel free to try it - the performance reduction may be irrelevant, depending upon your application: f=open("myFile.txt","w+",0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.