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.
How to check if file exists?
Re: How to check if file exists?
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
Re: How to check if file exists?
Thank you I'll give it a try.
Re: How to check if file exists?
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.
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.
Re: How to check if file exists?
Something like this should work:
If you want to determine if filename is a directory or a regular file then you can write:
Code: Select all
import os
def file_or_dir_exists(filename):
try:
os.stat(filename)
return True
except OSError:
retrun False
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
Re: How to check if file exists?
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')
import os
if 'my_file' in os.listdir(): print('found it')