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:15
import os
import tempfile

root = tempfile.gettempdir()
EMPTYDIRS = []

for path, subdirs, files in os.walk(r'' + root ):
    if len( files ) == 0 and len( subdirs ) == 0:
        EMPTYDIRS.append( path )

for e in EMPTYDIRS:
    print e
查看更多
forever°为你锁心
3楼-- · 2020-02-17 09:17

Try:

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

or

if os.listdir(dir) == []:
    print "Empty"
查看更多
相关推荐>>
4楼-- · 2020-02-17 09:17

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 .

查看更多
\"骚年 ilove
5楼-- · 2020-02-17 09:18

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')
查看更多
够拽才男人
6楼-- · 2020-02-17 09:20

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)
查看更多
家丑人穷心不美
7楼-- · 2020-02-17 09:25
import os

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

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

查看更多
登录 后发表回答