Writing to a text file on the pyboard fails ?.

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
alexsunny123
Posts: 1
Joined: Sun Mar 14, 2021 12:33 pm

Writing to a text file on the pyboard fails ?.

Post by alexsunny123 » Sun Mar 14, 2021 12:34 pm

Hello,


In this example, the expectation is that I ought to be able to read back exactly what I put into the file. What I actually get back is an empty file.

It occurred to me that this might actually be an expected behavior, and that perhaps there is a manual technique that allows me to flush the file?
CODE: SELECT ALL

Code: Select all

Micro Python v1.3.3 on 2014-10-02; PYBv1.0 with STM32F405RG
Type "help()" for more information.
>>> import os
>>> os.listdir()
['main.py', 'pybcdc.inf', 'README.txt', 'boot.py', '.Trash-1000']
>>> open("foo.txt", "w").write("hello world")
11
>>> os.listdir()
['main.py', 'pybcdc.inf', 'README.txt', 'boot.py', 'foo.txt', '.Trash-1000']
>>>
>>> open("foo.txt").read()
''
The use case here, is that I want to do stuff like:
* Periodically record something to a local text file, either in pyboard memory or on the SD card.
* As part of a code deployment process, automatically generate ,py files on the pyboard which can then be executed.


thanks
alexsunny

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Writing to a text file on the pyboard fails ?.

Post by Roberthh » Sun Mar 14, 2021 1:01 pm

You should close the file, or use a "with ..." clause.

Code: Select all

f = open("foo.txt", "w")
f.write("hello world")
f.close()
or:

Code: Select all

with open("foo.txt", "w") as f:
    f.write("hello world")

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Writing to a text file on the pyboard fails ?.

Post by pythoncoder » Sun Mar 14, 2021 2:54 pm

The "with" context manager is preferable because the file will always be closed, even if an exception occurs.
Peter Hinch
Index to my micropython libraries.

User avatar
rcolistete
Posts: 352
Joined: Thu Dec 31, 2015 3:12 pm
Location: Brazil
Contact:

Re: Writing to a text file on the pyboard fails ?.

Post by rcolistete » Tue Mar 16, 2021 4:25 am

Remember to sync the buffer with the file system after closing the file. For Pyboard, it is the pyb.sync() function :

Code: Select all

pyb.sync()
My "MicroPython Samples". My "MicroPython Firmwares" with many options (double precision, ulab, etc).

Post Reply