Answers for "how to find dir and file in python"

1

python find file in directory

# option A (i think this is faster, not in micropython)

import os

if os.path.isfile("test.dat"):
	print("yes") #file found
else:
	print("no") #file not found

# also this is posible
# from os.path import isfile
# if isfile("test.dat"):


# option B (posible in micropython)

import os

if "test.dat" in os.listdir():
	print("yes") # file found
else:
	print("no") # file not found

# os.lisdir() return a array whit all the files found in the directory
Posted by: Guest on March-29-2021
0

find directory in directory python

import os

def listdir_r(dirpath):
  	"""lists directories and sub-directories recursively. 
    """
    paths=[]
    paths.append(dirpath)
    for path in os.listdir(dirpath):
        rpath = os.path.join(dirpath, path)
        if os.path.isdir(rpath):
            subdirs = listdir_r(rpath)
            if not subdirs == []:
                paths.extend(subdirs)
    return paths

# print the list of sub-directories
print(listdir_r('./'))
Posted by: Guest on June-09-2021

Python Answers by Framework

Browse Popular Code Answers by Language