Location is directory or file

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Lixas
Posts: 10
Joined: Fri Aug 21, 2020 9:09 am

Location is directory or file

Post by Lixas » Wed Dec 01, 2021 7:59 pm

Hello
What are my options to know, is location exists, is it a file or directory ?

User avatar
karfas
Posts: 193
Joined: Sat Jan 16, 2021 12:53 pm
Location: Vienna, Austria

Re: Location is directory or file

Post by karfas » Wed Dec 01, 2021 8:31 pm

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.
A few hours of debugging might save you from minutes of reading the documentation! :D
My repositories: https://github.com/karfas

User avatar
scruss
Posts: 360
Joined: Sat Aug 12, 2017 2:27 pm
Location: Toronto, Canada
Contact:

Re: Location is directory or file

Post by scruss » Wed Dec 01, 2021 8:38 pm

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

Lixas
Posts: 10
Joined: Fri Aug 21, 2020 9:09 am

Re: Location is directory or file

Post by Lixas » Wed Dec 01, 2021 8:55 pm

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 :)

Post Reply