Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #62604

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

Date 2013-12-23 00:33 -0800
From Gary Herron <gary.herron@islandtraining.com>
Subject Re: 2nd Try: Trouble writing lines to file that include line feeds - Newbie
References <f4f962d9-0e23-4b33-ba88-ce61afbb3418@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.4540.1387788095.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

2nd Try: Trouble writing lines to file that include line feeds - Newbie Dan Healy <daniel.t.healy@gmail.com> - 2013-12-22 16:55 -0800
  Re: 2nd Try: Trouble writing lines to file that include line feeds - Newbie Gary Herron <gary.herron@islandtraining.com> - 2013-12-23 00:33 -0800

csiph-web