WelcomeWelcome | FAQFAQ | DownloadsDownloads | WikiWiki

Author Topic: Micropython + file writing  (Read 5460 times)

Offline gavinmc42

  • Sr. Member
  • ****
  • Posts: 301
Micropython + file writing
« on: October 29, 2015, 12: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')

Offline bmarkus

  • Administrator
  • Hero Member
  • *****
  • Posts: 7183
    • My Community Forum
Re: Micropython + file writing
« Reply #1 on: October 29, 2015, 01: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))
Béla
Ham Radio callsign: HA5DI

"Amateur Radio: The First Technology-Based Social Network."

Offline gavinmc42

  • Sr. Member
  • ****
  • Posts: 301
Re: Micropython + file writing
« Reply #2 on: October 29, 2015, 07: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