View Full Version : Basic python programming - check if directory is empty

December 23rd, 2008, 11:41 PM
I want to check for the presence of files in a directory...

Can anyone tell me what I am doing wrong here?

import os, time, shutil, sys

work_path = '/home/chris/test/'

if os.listdir(work_path)=="":
print "yes"
print "No"

December 24th, 2008, 12:14 AM
os.listdir returns a list of files/subdirectories, not a string.


import os
path = '/home/chris/test'
if os.listdir(path) == []:
print "yes"
print "no"

There are probably more "pythonic" ways to do the comparison, but it works.

Tony Flury
December 24th, 2008, 12:21 AM
listdir returns a list - not a string - so it will never equal ""

you could use

if os.listdir(work_path) = []:


if not os.listdir(work_path):


if len(os.listdir(work_path)) > 0:

Take your pick - the middle one is pretty common - since an empty list is always evaluated as False.

December 24th, 2008, 12:25 AM
if os.listdir(work_path) = []:

Tiny bug there. ;)

I prefer the second one. Fewer symbols.

Tony Flury
December 24th, 2008, 03:02 PM
Unless otherwise stated - all code posted by me is untested :-) - I will have to add that to me signature :-)

Ty for pointing it out