Python: Check if any file exists in a given directory

三世轮回 提交于 2021-01-27 04:53:59

问题


Given a directory as a string, how can I find if ANY file exists in it?

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

My objective is to check if a path is devoid of files only (not sub-directories too).


回答1:


To only check one specific directory, a solution like this would suffice:

from os import listdir
from os.path import isfile, join

def does_file_exist_in_dir(path):
    return any(isfile(join(path, i)) for i in listdir(path))

To dissect what is happening:

  • The method does_file_exist_in_dir will take your path.
  • Using any it will return True if a file is found by iterating through the contents of your path by calling a listdir on it. Note the use of join for the path in order to provide a qualified filepath name to properly check.

As an option, if you want to traverse through all sub-directories of a given path and check for files, you can use os.walk and just check to see if the level you are in contains any files like this:

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


来源:https://stackoverflow.com/questions/33463325/python-check-if-any-file-exists-in-a-given-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!