os.walk('.') in micropython

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
nodepythoner
Posts: 11
Joined: Sat Apr 20, 2019 8:44 am

os.walk('.') in micropython

Post by nodepythoner » Sun Apr 21, 2019 7:28 pm

how to realize os.walk() command in micropython
i need to take all content in flash(files in other directories)
but os has not that command :(

Online
User avatar
dhylands
Posts: 3504
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: os.walk('.') in micropython

Post by dhylands » Mon Apr 22, 2019 12:02 am

You can use os.listdir() to get a list of all files in a directory and os.stat to determine which of those are directories and recurse.

This is what rshell does for its rsync command.

You could also take the os.walk implementation from here: https://github.com/micropython/micropyt ... __.py#L147

nodepythoner
Posts: 11
Joined: Sat Apr 20, 2019 8:44 am

Re: os.walk('.') in micropython

Post by nodepythoner » Mon Apr 22, 2019 6:22 am

THANKS! :)
i wrote changed code:

Code: Select all

import uos
files=[]
dirs=[]
def S_ISDIR(fname):
    try:
        f = open(fname, "r")
        exists = True
        f.close()
    except OSError:
        exists = False
    return(exists)
def walk(top):
    for dirent in uos.ilistdir(top):
        #print(dirent)
        mode = dirent[1] << 12
        fname = dirent[0]
        if S_ISDIR(fname):
            dirs.append(fname)
        else:
            files.append(fname)
    yield top, dirs, files
    for d in dirs:
        yield from walk(top + "/" + d)
for top, dirs, files in walk('/sd'):
    print(dirs,files)

i changed isdir function(tryes open a file. you cant open a dir)

Post Reply