How to check if file exists?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
donmerch
Posts: 11
Joined: Sat Mar 28, 2020 3:07 pm

How to check if file exists?

Post by donmerch » Sun Apr 05, 2020 7:11 pm

Hi. New to MicroPython, this forum and have my new PyBoard. I've gotten quite a bit of code written for using a rotary encoder and 4x20 LCD display and am now to the point of wanting to store a small list of 3 integers in a file on flash. I've used the json method that I've found here on the forum and it works great to write and read the file. However I'm looking for a way to see if the file exists. I had seen os.path.exists('somefile') but get an error about the path command not existing in os module.

Any ideas?
Thanks.

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: How to check if file exists?

Post by Roberthh » Sun Apr 05, 2020 8:05 pm

You can use the try/execpt mechanism of Python, trying to open the file, or "stat" the file. e.g.:

Code: Select all

try:
    f = open(filename, "r")
    # continue with the file.
except OSError:  # open failed
   # handle the file open case

donmerch
Posts: 11
Joined: Sat Mar 28, 2020 3:07 pm

Re: How to check if file exists?

Post by donmerch » Sun Apr 05, 2020 8:37 pm

Thank you I'll give it a try.

User avatar
EliAaron
Posts: 6
Joined: Thu Feb 24, 2022 1:35 pm
Location: Jerusalem, Israel
Contact:

Re: How to check if file exists?

Post by EliAaron » Mon Jun 27, 2022 7:01 pm

Here is another way to check if a file or folder exists.
This solution does not use open/close, try/except.
It does not check if the path is a file or folder.

Code: Select all

# Check if path exists.
# Works for relative and absolute path.
def path_exists(path):
    parent = ""  # parent folder name
    name = path  # name of file/folder

    # Check if file/folder has a parent folder
    index = path.rstrip('/').rfind('/')
    if index >= 0:
        index += 1
        parent = path[:index-1]
        name = path[index:]

    # Searching with iterator is more efficient if the parent contains lost of files/folders
    # return name in uos.listdir(parent)
    return any((name == x[0]) for x in uos.ilistdir(parent))
Last edited by EliAaron on Tue Sep 06, 2022 1:16 pm, edited 1 time in total.

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

Re: How to check if file exists?

Post by dhylands » Mon Jun 27, 2022 8:22 pm

Something like this should work:

Code: Select all

import os
def file_or_dir_exists(filename):
    try:
        os.stat(filename)
        return True
    except OSError:
        retrun False
If you want to determine if filename is a directory or a regular file then you can write:

Code: Select all

import os
def dir_exists(filename):
    try:
        return (os.stat(filename)[0] & 0x4000) != 0
    except OSError:
        return False
        
def file_exists(filename):
    try:
        return (os.stat(filename)[0] & 0x4000) == 0
    except OSError:
        return False

KJM
Posts: 158
Joined: Sun Nov 18, 2018 10:53 pm
Location: Sydney AU

Re: How to check if file exists?

Post by KJM » Tue Jun 28, 2022 6:26 am

If you're a simple soul like me & chuck most everything in the root directory.....
import os
if 'my_file' in os.listdir(): print('found it')

Post Reply