Tiny Core Linux

Tiny Core Base => Raspberry Pi => Topic started by: gavinmc42 on October 29, 2015, 03:47:02 AM

Title: Micropython + file writing
Post by: gavinmc42 on October 29, 2015, 03:47:02 AM
Having trouble writing files with micropython.

data = 123
file = open('/home/tc/filename.txt', 'w')
file.write(data)

I get the error "TypeError: object with buffer protocol required"
I have no problem writing text, this works
file.write('data')
Title: Re: Micropython + file writing
Post by: bmarkus on October 29, 2015, 04:10:45 AM
What do you want to write to the file? data is an integer class object with actual value 123. Do you want to write the object or the value to the file, as a binary value or as text? Please note, MicroPython is a Python 3.4 system.

Just to write content as a text use

Code: [Select]
file.write('%d\n' % (data))
Title: Re: Micropython + file writing
Post by: gavinmc42 on October 29, 2015, 10:07:40 PM
Thanks Bela,

Forgot it was 3.4, last time I did python it was 2.7.

file.write('%s\n' %(data)) is what I needed.
It seems to append the data but I opened the file as w not w+
With \n I get a newline, without it is just get added at the end of the first line.

file.open...
file.write...
file.close...

Opening, writing then closing works, keeping the file open the data got appended.
All it is doing is storing an incrementing count value that websocketd then pushes to the browser.

I better brush up on 3.4 Python.

This also helped with sleeping python to save cpu cycles, no import time python library yet so I did this.
os.system('sleep ' '%s' %(sleeptime)), probably lose a bunch of cycles calling os.xxx but sleeptime is in seconds anyway.

Regards
Gavin