[Tutor] Write Data to Multiple Files

Alan Gauld alan.gauld at yahoo.co.uk
Wed Apr 19 07:14:50 EDT 2017


On 19/04/17 11:35, Mohanad Ismail via Tutor wrote:

> Read data from serial and write to file 1 for 15 sec, 
> after the 15 seconds continue writing the data on to
> file 2 for 15 seconds
>... each file should write for 15 seconds and stop for 15 seconds

> Code:
> #!/usr/bin/env python
> from datetime import datetimeimport serial
> outfile='/home/bogie/Documents/Data/file1.txt'#outfile='/home/bogie/Documents/Data/file2.txt'ser = serial.Serial(    port='/dev/ttyS4',    baudrate=9600,    parity=serial.PARITY_NONE,    stopbits=serial.STOPBITS_ONE,    bytesize=serial.EIGHTBITS,
> )
> while ser.isOpen():    d = open(outfile,'a')     dataString = ser.read(44)    d.write(datetime.utcnow().isoformat()+ '\t' + dataString + '\n')    d.flush() #included to force the system to write to disk
> 
> ser.close()

This is a text only list and as such html formatting tends to
get wrecked so we can't read your code. Please use plain text
in future posts please?

Meanwhile, the hardest bit of what you want to do is checking
that 15s have elapsed. Actually opening two files and writing
to them is straightforward.

For the time bit I'd probably use the simpler time module
and its time() function rather than datetime, since you
are only interested in seconds which is what time() gives you.

Set an initial start counter using time.time() and on every
write iteration set a now value. When now-start >= 15 swap
to the other file and set start to now. repeat until done.

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list