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

CharlesB
  • 86,532
  • 28
  • 194
  • 218
aeupinhere
  • 2,883
  • 6
  • 31
  • 39

8 Answers8

64
import os

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

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

Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
  • 2
    If the directory contains thousands of files, would `os.listdir(dir)` return size be a issue? @Corey Goldberg – alper May 01 '20 at 16:27
48

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.

Peter Sutton
  • 1,145
  • 7
  • 20
mouad
  • 67,571
  • 18
  • 114
  • 106
  • 2
    +1: Simple. Direct. And it delegates **all** the tricky decision-making to the OS where it belongs. – S.Lott Jun 02 '11 at 13:56
  • 1
    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 :-) – André Caron Jan 08 '14 at 16:51
  • 2
    How about `else: raise`? – spectras Sep 07 '15 at 17:05
  • 2
    nice but: `NameError: name 'errno' is not defined` you need `import errno`! – ewerybody Jan 11 '18 at 16:55
17

Try:

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

or

if os.listdir(dir) == []:
    print "Empty"
dogbane
  • 266,786
  • 75
  • 396
  • 414
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)
ideasman42
  • 42,413
  • 44
  • 197
  • 320
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)
kafuchau
  • 5,573
  • 7
  • 33
  • 38
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')
Jakob
  • 119
  • 1
  • 6
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 .

Natesh bhat
  • 12,274
  • 10
  • 84
  • 125
  • 1
    Using `os.scandir` is fast, with the advantage of being clearer and not needing to generate lists that aren't use. – ideasman42 Sep 23 '19 at 08:07
0

I have follews Bash checking if folder has contents answer.

Mainly it is similiar approach as @ideasman42's answer on https://stackoverflow.com/a/47363995/2402577, 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")
alper
  • 2,919
  • 9
  • 53
  • 102