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

Gary Herron gary.herron at islandtraining.com
Mon Dec 23 03:33:24 EST 2013


On 12/22/2013 04:55 PM, Dan Healy wrote:
> 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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20131223/7f334a53/attachment.html>


More information about the Python-list mailing list