MicroPython 'os' Module
Contents
Getting Started
Standard microcontrollers typically do not run a traditional operating system (OS) like Windows or Linux. MicroPython firmware serves as primary (albeit simple) software environment.
The MicroPython os module provides a very basic set of commands (methods) to perform filesystem operations. The methods are generally simple to use in the REPL as well as scripted programs. They mostly provide all that's needed in a simple processing environment.
The examples given below to illustrate method usage are in their simplest form. It's important to note that most methods in the MicroPython os module can raise an OSError when a system-level operation fails. For critical operations it's prudent to wrap the method in a try/except OSError: block.
Attempting to delete a file that doesn't exist raises such an exception. The following is an example of how to catch this and gracefully deal with the exception:
import os
file ='/flash/data.txt'
# Attempt to delete 'data.txt' from flash.
try:
os.remove(file)
print("File deleted successfully")
except OSError as e:
print('Error:', e)
print('Unable to delete file:', file)
This code attempts to delete data.txt and handles the exception if the file doesn't exist or cannot be deleted. If the file doesn't exist the following will be returned:
Error: [Errno 2] ENOENT
Unable to delete file: /flash/data.txt
MicroPython os Methods
We've divided them logically into methods for directories, files and miscellaneous.
Methods for Directories
| Method | Description |
|---|---|
| getcwd() | Get current directory. |
| chdir(path) | Change current directory to path directory. |
| listdir() | List current directory. |
| listdir(dir) | List the directory dir. |
| mkdir(path) | Create the new directory path. |
| rename(old_path, new_path) | Rename a directory. |
| rmdir(path) | Delete the directory path. |
| stat(path) | Get the status of the directory path. Returns a tuple with 10 elements. |
Examples: import os os.getcwd() '/flash' os.listdir() ['boot.py', 'main.py', 'pybcdc.inf', 'README.txt'] os.listdir('/flash') ['boot.py', 'main.py', 'pybcdc.inf', 'README.txt'] os.mkdir('/flash/X') os.listdir('/flash') ['boot.py', 'main.py', 'pybcdc.inf', 'README.txt', 'X'] os.chdir('/flash/X') os.getcwd() '/flash/X' os.chdir('/flash') os.getcwd() '/flash' os.rename('X', 'Y') os.listdir() ['boot.py', 'main.py', 'pybcdc.inf', 'README.txt', 'Y'] os.rmdir('/flash/Y') os.listdir() ['boot.py', 'main.py', 'pybcdc.inf', 'README.txt'] os.stat('/flash') (16384, 0, 0, 0, 0, 0, 0, 0, 0, 0)
NOTE for stat() method: The first element of the tuple result ([0]) indicates whether the item is a directory or a file:
- Value = 16384 : Directory
- Value = 32768 : File
This is very useful when sorting through a directory listing.
Methods for Files
| Method | Description |
|---|---|
| rename(old_path, new_path) | Rename a file. |
| remove(path) | Delete a file. |
| stat(path) | Get the status of the file path. Returns a tuple with 10 elements. |
| stat(path)[6] | Get the size of the file path in bytes. |
Examples: import os os.listdir() ['boot.py', 'main.py', 'pybcdc.inf', 'README.txt'] os.rename('pybcdc.inf', 'silly.inf') os.listdir() ['boot.py', 'main.py', 'README.txt', 'silly.inf'] os.remove('silly.inf') os.listdir() ['boot.py', 'main.py', 'README.txt'] os.stat('/flash/README.txt') (32768, 0, 0, 0, 0, 0, 526, 94, 94, 94) os.stat('/flash/README.txt')[6] 526
Miscellaneous Methods
- os.ilistdir(dir)
Returns an iterator that yields tuples for each entry in a specified directory. When called without arguments, it lists the current directory; otherwise, it lists the directory given by the dir parameter.
This function is more memory-efficient than os.listdir() because it uses an iterator and avoids calling stat() for each entry, making it ideal for large directories or resource-constrained devices.
Each yielded tuple has the form (name, type, inode[, size]):- name: A string representing the entry's name.
- type: An integer indicating the entry type 16384 for directories and 32768 for regular files.
- inode: An integer corresponding to the file's inode (may be 0 on filesystems without inodes).
- size: An optional integer representing the file size in bytes (or -1 if unknown); this field may not be present on all platforms.
Example: import os # A listing of subdirectories and files is # required for each directory given in the # following list. DirList = ('/flash', '/flash/Data_Files') # Examine one by one each directory. for dir in DirList: print('\n**********************************') print('Dir listing for:', dir) print('**********************************') for entry in os.ilistdir(dir): # Unpack the tuple. name, type, inode, size = entry # Check whether entry is a directory. is_dir = (type & 0x4000) != 0 # Print out the entry if is_dir: print('[DIR] ' + name) else: print(name, size, 'bytes') Typical Output: ********************************** Dir listing for: /flash ********************************** boot.py 454 bytes main.py 34 bytes pybcdc.inf 2597 bytes i2c1_scan.py 171 bytes os_ilistdir_example.py 272 bytes uart_test_with_putty.py 257 bytes [DIR] Data_Files ********************************** Dir listing for: /flash/Data_Files ********************************** myfile.txt 12 bytes README.txt 526 bytes - os.sync()
Forces the synchronization of all mounted filesystems, ensuring that any pending write operations (such as file creations, modifications, or deletions) are physically written to the storage device.
This can be crucial for data integrity, especially before a system reset or power loss, as it prevents corruption by flushing internal buffers.
It is not available for all MicroPython ports.Example: import os # Write data to a file. with open('test.txt', 'w') as f: f.write('Hello, MicroPython!') # Ensure all data is written to storage. os.sync() print('File synced to disk.') - os.uname()
Returns a tuple containing information about the underlying system and MicroPython build. The five fields are:- sysname: Name of the underlying system (e.g., 'esp32', 'microbit').
- nodename: Network name (usually same as sysname).
- release: Version of the underlying system
- version: MicroPython version and build date
- machine: Hardware identifier (e.g., board or CPU type)
Example: import os t = os.uname() print('sysname:', t[0]) print('nodename:', t[1]) print('release:', t[2]) print('version:', t[3]) print('machine:', t[4]) Typical Output: sysname: esp32 nodename: esp32 release: 1.24.1 version: v1.24.1 on 2024-11-29 machine: Generic ESP32 module with ESP32 - os.urandom(n)
Returns a bytes object containing n random bytes. It uses the hardware random number generator when available, making it suitable for cryptographic purposes.
This function is commonly used to generate secure random data on microcontrollers.Example: import os # Generate 6 random bytes random_bytes = os.urandom(6) for byte in random_bytes: print(hex(byte), end=' ') print('\n') Typical Output: 0x51 0x1e 0xb9 0xe3 0xc2 0xb2
Microcontroller Bits and Pieces
Tools for Microcontrollers
dfu-util Utility
esptool Utility