Python: Check if any file exists in a given directory -


given directory string, how can find if file exists in it?

os.path.isfile()       # accepts specific file path os.listdir(dir) == []  # accepts sub-directories 

my objective check if path devoid of files (not sub-directories too).

to check 1 specific directory, solution suffice:

from os import listdir os.path import isfile, join  def does_file_exist_in_dir(path):     return any(isfile(join(path, i)) in listdir(path)) 

to dissect happening:

  • the method does_file_exist_in_dir take path.
  • using any return true if file found iterating through contents of path calling listdir on it. note use of join path in order provide qualified filepath name check.

as option, if want traverse through sub-directories of given path , check files, can use os.walk , check see if level in contains files this:

for dir, sub_dirs, files in os.walk(path):     if not files:         print("no files @ level") 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -