PDA

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



chrismyers
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?


#!/usr/bin/python
import os, time, shutil, sys

work_path = '/home/chris/test/'

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

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

Try:


import os
path = '/home/chris/test'
if os.listdir(path) == []:
print "yes"
else:
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) = []:

or


if not os.listdir(work_path):

or


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.

snova
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