2nd Try: Trouble writing lines to file that include line feeds - Newbie

D

Dan Healy

Overview: I'm attempting to read strings from a serial port. Each string ends with a carriage return and line feed. I want to write those strings to afile, like a log file. So, if I send P1 and the P2 on a new line, I would expect to open this file and find (line 1) P1 (line 2) P2.

Problem: The file only contains P2. It always overwrites the first line. I can send 20 strings and the file will always contain the last string received.

Code:

#Import the serial module
import serial

#Open the serial port w/ settings
ser=serial.Serial(
port="/dev/ttyUSB0",
baudrate=9600,
timeout=None)

#Print data received on the serial port after removing the CR and LF characters
while True:
rawcode=ser.readline()
codelog=open('/home/pi/avdms/codes.log','w')
codelog.write(rawcode)
codelog.close()
 
G

Gary Herron

Overview: I'm attempting to read strings from a serial port. Each string ends with a carriage return and line feed. I want to write those strings to a file, like a log file. So, if I send P1 and the P2 on a new line, I would expect to open this file and find (line 1) P1 (line 2) P2.

Problem: The file only contains P2. It always overwrites the first line. I can send 20 strings and the file will always contain the last string received.

Code:

#Import the serial module
import serial

#Open the serial port w/ settings
ser=serial.Serial(
port="/dev/ttyUSB0",
baudrate=9600,
timeout=None)

#Print data received on the serial port after removing the CR and LF characters
while True:
rawcode=ser.readline()
codelog=open('/home/pi/avdms/codes.log','w')
codelog.write(rawcode)
codelog.close()

First, that code is quite foolish: If you want to write multiple lines
to a file, open the file once before the loop, looped through all your
writes, and then closed it after the loop has exited.:

codelog=open('/home/pi/avdms/codes.log','w')
while True:
rawcode=ser.readline()
codelog.write(rawcode)

codelog.close()


However, on the chance that you are writing this code for testing
purposes, and you really do have a need to open a file, write something
onto the end and then close the file, and that you are going to do this
many times, I'll continue with this response:

The default behavior of the "open" call is to *truncate* (i.e.,
clear the contents) and start writing at the beginning. The
behavior you want is called *append*, and you get it with a 'wa' as
the second parameter of the open call.


See http://docs.python.org/3/library/functions.html#open for a list of
other modes available for the open call.

Gary Herron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top