Page 1 of 1

Location is directory or file

Posted: Wed Dec 01, 2021 7:59 pm
by Lixas
Hello
What are my options to know, is location exists, is it a file or directory ?

Re: Location is directory or file

Posted: Wed Dec 01, 2021 8:31 pm
by karfas
See https://docs.micropython.org/en/latest/library/os.html and
viewtopic.php?t=5291

It's really fascinating what a Google search (in this case: "Micropython directory") might return.

Re: Location is directory or file

Posted: Wed Dec 01, 2021 8:38 pm
by scruss

Code: Select all

import os

for loc in os.ilistdir('.'):
    if loc[1] == 0x4000:    # folder
        print(loc[0]+'/')
    else:                   # file
        print(loc[0]+':', loc[3], 'bytes')
Output, on the nearest Raspberry Pi Pico I could find:

Code: Select all

1602clock.py: 385 bytes
cardkb.py: 725 bytes
dir.py: 181 bytes
id.py: 102 bytes
lib/
rnd_spd2.py: 295 bytes
rnd_spd3.py: 273 bytes
tm1638tst.py: 215 bytes
touch.py: 136 bytes

Re: Location is directory or file

Posted: Wed Dec 01, 2021 8:55 pm
by Lixas
Google? never heard of it :shock:

This is what i came up with:

Code: Select all

def file_exists(path):
    try:
        f = open(path, "r")
        f.close()
        return True
    except OSError:
        return False

def dir_exists(path):
    try:
        if os.stat(path)[0] & 0x4000:
            return True
        else:
            return False
    except OSError:
        return False
Thanks for pointing me to 0x4000 direction :)