Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding empty directories in Python

Tags:

python

rmdir

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

like image 884
aeupinhere Avatar asked Jun 02 '11 13:06

aeupinhere


People also ask

How check if directory is empty?

To check whether a directory is empty or not os. listdir() method is used. os. listdir() method of os module is used to get the list of all the files and directories in the specified directory.

How do I find empty files and folders?

First, search all the empty files in the given directory and then, delete all those files. This particular part of the command, find . -type f -empty -print, will find all the empty files in the given directory recursively.


2 Answers

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

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

like image 180
Corey Goldberg Avatar answered Oct 01 '22 13:10

Corey Goldberg


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.

like image 24
mouad Avatar answered Oct 01 '22 11:10

mouad