Skip to content

MicroPython: Filesystem

Leo Vidarte edited this page Mar 6, 2017 · 2 revisions

The internal filesystem

If your devices has 1 Mbyte or more of storage then it will be set up (upon first boot) to contain a filesystem. This filesystem uses the FAT format and is stored in the flash after the MicroPython firmware.

Creating and reading files

To create a file try:

>>> f = open('data.txt', 'w')
>>> f.write('some data')
9
>>> f.close()

Then you can read back the contents of this new file using:

>>> f = open('data.txt')
>>> f.read()
'some data'
>>> f.close()

Listing file and more

The os module can be used for further control over the filesystem. First import the module:

>>> import os

Then try listing the contents of the filesystem:

>>> os.listdir()
['boot.py', 'port_config.py', 'data.txt']

You can make directories:

>>> os.mkdir('dir')

And remove entries:

>>> os.remove('data.txt')

Start up scripts

There are two files that are treated specially by the ESP8266 when it starts up: boot.py and main.py. The boot.py script is executed first (if it exists) and then once it completes the main.py script is executed. You can create these files yourself and populate them with the code that you want to run when the device starts up.

Accessing the filesystem via WebREPL

You can access the filesystem over WebREPL using the web client in a browser or via the command-line tool.

Accessing files with Ampy

Ampy (Adafruit MicroPython Tool) is an utility to interact with a MicroPython board over a serial connection.

Ampy is meant to be a simple command line tool to manipulate files and run code on a MicroPython board over its serial connection. With ampy you can send files from your computer to a MicroPython board's file system, download files from a board to your computer, and even send a Python script to a board to be executed.

pip3 install adafruit-ampy

Usage:

$ ampy --help

Usage: ampy [OPTIONS] COMMAND [ARGS]...

  ampy - Adafruit MicroPython Tool

  …

Options:
  -p, --port PORT  Name of serial port for connected board. 
  -b, --baud BAUD  Baud rate. (default 115200)
  --help           Show this message and exit.

Commands:
  get  Retrieve a file from the board.
  ls   List contents of a directory on the board.
  put  Put a file on the board.
  rm   Remove a file from the board.
  run  Run a script and print its output.

List files on board

$ ampy -p /dev/ttyUSB0 ls
boot.py
Webrepl_cfg.py