harshcht
Posts: 1
Joined: Fri May 18, 2018 6:54 am

Unable to write to a .txt file when using GPS

Fri May 18, 2018 7:08 am

I recently baught a GPS module and a r-pi3B. I am able to read GPS using gpsd and gpspipe.
But when I try to write to another file and read GPS serial port in the same loop it , nothing is written to the file.

code:

Code: Select all

import serial
import time
ser = serial.Serial('/dev/ttyS0'
     
)
f=open("file.txt","w+")
while 1:
        x=ser.readline()
        print (x)
        f.write('writing to file \n')
        
GPS data is displayed correctly and file.txt is created. But when I open it it is blank. Can anyone please help

B.Goode
Posts: 6179
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: Unable to write to a .txt file when using GPS

Fri May 18, 2018 9:14 am

Welcome to the Raspberry Pi forums.


Maybe you should close the file to ensure that data is written to it.

Even if you do that, you will only see "writing to file" many times, you do not write any gps data to the file.

scotty101
Posts: 2981
Joined: Fri Jun 08, 2012 6:03 pm

Re: Unable to write to a .txt file when using GPS

Fri May 18, 2018 9:38 am

As already mentioned you aren't actually writing the data from the serial port to the file. I've changed your code to add f.write(x) which will write the line from the serial port to the file.
I've also added a "context manager" to deal with opening and closing the file.
Untested code, but it should work.

Code: Select all

import serial
import time
ser = serial.Serial('/dev/ttyS0')


while 1:
    with open("file.txt","w+") as f
        x=ser.readline()
        print (x)
        f.write(x)
    time.sleep(0.5)
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Return to “Python”

Who is online

Users browsing this forum: No registered users and 14 guests