Finding empty directories in Python

2020-02-17 08:57发布

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

标签: python rmdir
8条回答
贼婆χ
2楼-- · 2020-02-17 09:26

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.

查看更多
迷人小祖宗
3楼-- · 2020-02-17 09:31

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):
    return next(os.scandir(path), None) is None
查看更多
登录 后发表回答