Finding empty directories in Python

左心房为你撑大大i 提交于 2019-11-30 11:36:04

问题


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


回答1:


import os

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

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




回答2:


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:


Try:

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

or

if os.listdir(dir) == []:
    print "Empty"



回答4:


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



回答5:


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)



回答6:


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')



回答7:


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 .




回答8:


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


来源:https://stackoverflow.com/questions/6215334/finding-empty-directories-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!