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 conta
Check if the folder contains files:
import os
import shutil
if len(os.listdir(folder_path)) == 0: # Check is empty..
shutil.rmtree(folder_path) # Delete..
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.
If you can delete the directory, you can use this:
my_path = os.path.abspath("something")
try:
os.rmdir(my_path)
is_empty = True
# Do you need to keep the directory? Recreate it!
# os.makedirs(my_path, exist_ok=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:
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.
You can directly use the generator instead of converting to a set or (ordered) list first:
from pathlib import Path
p = Path('abc')
def check_dir(p):
if not p.exists():
print('This directory is non-existent')
return
try:
next(p.rglob('*'))
except StopIteration:
print('This directory is empty')
return
print('OK')
entities = os.listdir(dirpath)
for entity in entities:
if os.path.isfile(entity):
print(dirpath)
break
'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')