Finding empty directories in Python
Asked Answered
D

8

44

All,

What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.

dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.

Thanks, Adam

Dongdonga answered 2/6, 2011 at 13:42 Comment(5)
Define "empty". What if there are subdirectories? Should they be checked for data? Should they also be deleted if there is no data in them?Imperception
I don't have any subdirectories in this case just a single folder that may or may not have pics in it.Dongdonga
Please do not use os.system to call wget. Use subprocess.PopenSporozoite
In essence: isempty = lambda path : not next(os.scandir(path), None)Willson
Don't use os.listdir or try, except statements. os.scandir is orders of magnitude faster.Willson
K
64
import os

if not os.listdir(dir):
    os.rmdir(dir)

LBYL style.
for EAFP, see mouad's answer.

Kaslik answered 2/6, 2011 at 13:48 Comment(1)
If the directory contains thousands of files, would os.listdir(dir) return size be a issue? @Corey GoldbergPhyfe
A
49

I will go with EAFP like so:

try:
    os.rmdir(dir)
except OSError as ex:
    if ex.errno == errno.ENOTEMPTY:
        print "directory not empty"

os.rmdir will not delete a directory that is not empty.

Agripinaagrippa answered 2/6, 2011 at 13:51 Comment(4)
+1: Simple. Direct. And it delegates all the tricky decision-making to the OS where it belongs.Manifold
Note that this function silently drops all other errors (such as EACCESS), which you may want to report. Note that fixing that naively would probably result in reporting errors for non-empty directories, which you probably want to ignore. Not as simple as it seems :-)Lonnielonny
How about else: raise?Lowly
nice but: NameError: name 'errno' is not defined you need import errno!Ambroid
F
17

Try:

if not os.listdir(dir): 
    print "Empty"

or

if os.listdir(dir) == []:
    print "Empty"
Fanjet answered 2/6, 2011 at 13:48 Comment(0)
A
11

This can now be done more efficiently in Python3.5+, since there is no need to build a list of the directory contents just to see if its empty:

import os

def is_dir_empty(path):
    with os.scandir(path) as scan:
        return next(scan, None) is None

Example usage:


if os.path.isdir(directory) and is_dir_empty(directory):
    os.rmdir(directory)
Acetone answered 18/11, 2017 at 8:13 Comment(0)
F
2

What if you did checked if the directory exists, and whether there is content in the directory... something like:

if os.path.isdir(dir) and len(os.listdir(dir)) == 0:
    os.rmdir(dir)
Frigorific answered 2/6, 2011 at 13:49 Comment(0)
R
1

If the empty directories are already created, you can place this script in your outer directory and run it:

import os

def _visit(arg, dirname, names):
    if not names:
        print 'Remove %s' % dirname
        os.rmdir(dirname)

def run(outer_dir):
    os.path.walk(outer_dir, _visit, 0)

if __name__ == '__main__':
    outer_dir = os.path.dirname(__file__)
    run(outer_dir)
    os.system('pause')
Ravioli answered 20/5, 2016 at 14:51 Comment(0)
P
1

Here is the fastest and optimized way to check if the directory is empty or not.

empty = False
for dirpath, dirnames, files in os.walk(dir):
    if files:
        print("Not empty !") ;
    if not files:
        print("It is empty !" )
        empty = True
    break ;

The other answers mentioned here are not fast because , if you want use the usual os.listdir() , if the directory has too many files , it will slow ur code and if you use the os.rmdir( ) method to try to catch the error , then it will simply delete that folder. This might not be something which u wanna do if you just want to check for emptyness .

Pollack answered 14/5, 2018 at 11:47 Comment(1)
Using os.scandir is fast, with the advantage of being clearer and not needing to generate lists that aren't use.Acetone
P
0

I have follews Bash checking if folder has contents answer.

Mainly it is similiar approach as @ideasman42's answer on https://mcmap.net/q/369488/-finding-empty-directories-in-python, in order to not to build the complete list, which would probably work on Debian as well.

there is no need to build a list of the directory contents just to see if its empty:


os.walk('.') returns the complete files under a directory and if there thousands it may be inefficient. Instead following command find "$target" -mindepth 1 -print -quit returns first found file and quits. If it returns an empty string, which means folder is empty.

You can check if a directory is empty using find, and processing its output

def is_dir_empty(absolute_path):
    cmd = ["find", absolute_path, "-mindepth", "1", "-print", "-quit"]
    output = subprocess.check_output(cmd).decode("utf-8").strip()
    return not output

print is_dir_empty("some/path/here")
Phyfe answered 1/5, 2020 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.