Skip to content

Latest commit

 

History

History
133 lines (99 loc) · 5.19 KB

filesystem.rst

File metadata and controls

133 lines (99 loc) · 5.19 KB

Local Persistent File System

It is useful to store data in a persistent manner so that it remains intact between restarts of the device. On traditional computers this is often achieved by a file system consisting of named files that hold raw data, and named directories that contain files. Python supports the various operations needed to work with such file systems.

However, since the micro:bit is a limited device in terms of both hardware and storage capacity MicroPython provides a small subset of the functions needed to persist data on the device. Because of memory constraints there is approximately 30k of storage available on the file system.

Warning

Re-flashing the device will DESTROY YOUR DATA.

Since the file system is stored in the micro:bit's flash memory and flashing the device rewrites all the available flash memory then all your data will be lost if you flash your device.

However, if you switch your device off the data will remain intact until you either delete it (see below) or re-flash the device.

MicroPython on the micro:bit provides a flat file system; i.e. there is no notion of a directory hierarchy, the file system is just a list of named files. Reading and writing a file is achieved via the standard Python open function and the resulting file-like object (representing the file) of types TextIO or BytesIO. Operations for working with files on the file system (for example, listing or deleting files) are contained within the :pyos module.

If a file ends in the .py file extension then it can be imported. For example, a file named hello.py can be imported like this: import hello.

An example session in the MicroPython REPL may look something like this:

>>> with open('hello.py', 'w') as hello:
...    hello.write("print('Hello')")
...
>>> import hello
Hello
>>> with open('hello.py') as hello:
...   print(hello.read())
...
print('Hello')
>>> import os
>>> os.listdir()
['hello.py']
>>> os.remove('hello.py')
>>> os.listdir()
[]