Skip to content

Instantly share code, notes, and snippets.

@romilly
Created July 17, 2022 12:23
Show Gist options
  • Save romilly/5a1ff86d1e4d87e084b76d5651f23a40 to your computer and use it in GitHub Desktop.
Save romilly/5a1ff86d1e4d87e084b76d5651f23a40 to your computer and use it in GitHub Desktop.
Delete all files and directories from a micropython file-system (including .py files)
# ***WARNING***
# Running this file will delete all files and directories from the micropython device it's running on
# If you run keep_this=False it will delete this file as well.
# see https://docs.micropython.org/en/latest/library/os.html for os function list
import os
def _delete_all(directory='.', keep_this=True):
try:
import machine
except:
# not a micropython board so exit gracefully
print('Not a micro-python board! Leaving it well alone.')
return
for fi in os.ilistdir(directory):
fn, ft = fi[0:2] # can be 3 or 4 items returned!
if keep_this and fn == '_nuke.py':
continue
fp = '%s/%s' % (directory, fn)
print('removing %s' % fp)
if ft == 0x8000:
os.remove(fp)
else:
_delete_all(fp)
os.rmdir(fp)
_delete_all()
@romilly
Copy link
Author

romilly commented Jul 17, 2022

I needed this to help me create an automated deployment process.

@alanvgreen
Copy link

Me too! Thank you for sharing this.

@PolarGoose
Copy link

Great script. Thanks a lot.
The only thing is that it also removes boot.py, which is probably not desirable.
I have adjusted the script a bit to remove all the files from the board except boot.py:

import os


try:
    import machine
except ImportError:
    print('This script can only be run on a MicroPython device')
    exit(1)


def delete_all_files_and_directories(directory):
    for file_info in os.ilistdir(directory):
        file_name, file_type = file_info[0:2]
        if file_name == 'boot.py':
            continue
        file_full_name = f"{directory}/{file_name}"
        print(f"Remove {file_full_name}")
        if file_type == 0x8000: # file
            os.remove(file_full_name)
        else:
            delete_all_files_and_directories(file_full_name)
            os.rmdir(file_full_name)


delete_all_files_and_directories("/")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment