How to check to see if a folder contains files usi

2019-01-09 12:26发布

问题:

I've searched everywhere for this answer but can't find it.

I'm trying to come up with a script that will search for a particular subfolder then check if it contains any files and, if so, write out the path of the folder. I've gotten the subfolder search part figured out, but the checking for files is stumping me.

I have found multiple suggestions for how to check if a folder is empty, and I've tried to modify the scripts to check if the folder is not empty, but I'm not getting the right results.

Here is the script that has come the closest:

for dirpath, dirnames, files in os.walk('.'):
if os.listdir(dirpath)==[]:
    print(dirpath)

This will list all subfolders that are empty, but if I try to change it to:

if os.listdir(dirpath)!=[]:
    print(dirpath)

it will list everything--not just those subfolders containing files.

I would really appreciate it if someone could point me in the right direction.

This is for Python 3.4, if that matters.

Thanks for any help you can give me.

回答1:

'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')


回答2:

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.



回答3:

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


回答4:

If you can delete the folder, 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 folder 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 folder is fine when you are planing to do a git clone, but you are checking beforehand whether the folder is empty so git does not throw the not empty folder error.



回答5:

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.