The MicroPython language has a feature that allows you to read, write, and delete files. You can have multiple files and the Mu editor allows you to access them directly via it's Files button in the menu bar.files in mu beta



However, if what you really want to do is just store a single number in non volatile memory so that it is retained when the micro:bit is turned off, and retrieve it again when you turn the micro:bit on, it's not immediately obvious how you would do this.


One relatively simple way to meet this need of storing and retrieving values in the non-volatile memory, is to just use a file with a single value written to it. If you only have one or two values to store, just use more files. Here is an example of such a solution, that includes various error checks and recovery modes for things like the file not existing, the file having invalid data in it, or the filing system becoming full up:

   

from microbit import *

def get_nv_data(name):
    try:
        with open(name) as f:
            v = int(f.read())
    except OSError:
        v = 0
        try:
            with open(name, "w") as f:
               f.write(str(v))
        except OSError:
            print("Can't create file %s" % name)

    except ValueError:
        print("invalid data in file %s" % name)
        v = 0

    return v

def set_nv_data(name, value):
    try:
        with open(name, "w") as f:
            f.write(str(value))
    except OSError:
        print("Can't write to file %s" % name)


count = get_nv_data("data.txt")
display.show(count)

count = count + 1
set_nv_data("data.txt", count)

   

Every time you press the reset button on the back of the micro:bit, it will add one to the stored number and re-display it.

If you remove the power from your micro:bit and later plug it in, it will have remembered that number.


Further Information 

The above code is an example of how to store one integer variable value in a text file. We hope to write a more flexible example in the future, that allows any number of data variables to be read and written from a single file (e.g. like a config file).


The full version of Python has a 'pickle' module that allows arbitrary data values to be stored to files. Also there is a dbm module, which allows a mini key-value database to be stored in a file. Neither of these modules have been ported into the standard distribution of MicroPython on the micro:bit.


Keywords for search: nonvolatile, non volatile, non-volatile, variable, persistent, lost, micropython, python, store, retrieve, remember, remembered, off