How to check to see if a folder contains files using python 3

人走茶凉 提交于 2019-11-27 09:11:45
tdelaney

'files' already tells you whats in the directory. Just check it:

for dirpath, dirnames, files in os.walk('.'):
    if files:
        print(dirpath, 'has files')
    if not files:
        print(dirpath, 'is empty')

You can make use of the new pathlib library introduced in Python 3.4 to extract all non-empty subdirectories recursively, eg:

import pathlib

root = pathlib.Path('some/path/here')
non_empty_dirs = {str(p.parent) for p in root.rglob('*') if p.is_file()}

Since you have to walk the tree anyway, we build a set of the parent directories where a file is present which results in a set of directories that contain files - then do as you wish with the result.

entities = os.listdir(dirpath)
for entity in entities:
    if os.path.isfile(entity):
        print(dirpath)
        break

If you can delete the directory, you can use this:

try:
    os.rmdir( submodule_absolute_path )
    is_empty = True

except OSError:
    is_empty = False

if is_empty:
    pass

The os.rmdir only removes a directory if it is empty, otherwise it throws the OSError exception.

You can find a discussion about this on:

  1. https://bytes.com/topic/python/answers/157394-how-determine-if-folder-empty

For example, deleting an empty directory is fine when you are planing to do a git clone, but not if you are checking beforehand whether the directory is empty, so your program does not throw an empty directory error.

Adding to @Jon Clements’ pathlib answer, I wanted to check if the folder is empty with pathlib but without creating a set:

from pathlib import Path

is_empty = not bool(sorted(Path('some/path/here').rglob('*')))

sorted(Path(path_here).rglob('*')) return a list of sorted PosixPah items. If there is no items, it returns an empty list, which is False. So is_empty will be True if the path is empty and false if the path have something

Similar idea results {} and [] gives the same:

You can use this simple code:

dir_contents = [x for x in os.listdir('.') if not x.startswith('.')]
if len(dir_contents) > 0:
    print("Directory contains files")

It checks for files and directories in the current working directory (.). You can change . in os.listdir() to check any other directory.

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