Results 1 to 5 of 5

Thread: Basic python programming - check if directory is empty

  1. #1
    Join Date
    Apr 2006
    Location
    Leeds, England
    Beans
    173
    Distro
    Ubuntu 11.10 Oneiric Ocelot

    Basic python programming - check if directory is empty

    I want to check for the presence of files in a directory...

    Can anyone tell me what I am doing wrong here?

    Code:
    #!/usr/bin/python
    import os, time, shutil, sys
    
    work_path = '/home/chris/test/'
    
    if os.listdir(work_path)=="":
        print "yes"
    else:
        print "No"
    The Ubuntu Counter Project - User number # 6435

  2. #2
    Join Date
    May 2008
    Beans
    Hidden!

    Re: Basic python programming - check if directory is empty

    os.listdir returns a list of files/subdirectories, not a string.

    Try:

    PHP Code:
    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.

  3. #3
    Join Date
    May 2008
    Location
    UK
    Beans
    1,450
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: Basic python programming - check if directory is empty

    listdir returns a list - not a string - so it will never equal ""

    you could use
    Code:
    if os.listdir(work_path) = []:
    or
    Code:
    if not os.listdir(work_path):
    or
    Code:
    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.
    Tony - Happy to try to help.
    Unless otherwise stated - all code posted by me is untested. Remember to Mark the Thread as Solved.
    Ubuntu user number # 24044 Projects : TimeWarp - on the fly Backups

  4. #4
    Join Date
    May 2008
    Beans
    Hidden!

    Re: Basic python programming - check if directory is empty

    Quote Originally Posted by Tony Flury View Post
    Code:
    if os.listdir(work_path) = []:
    Tiny bug there.

    I prefer the second one. Fewer symbols.

  5. #5
    Join Date
    May 2008
    Location
    UK
    Beans
    1,450
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: Basic python programming - check if directory is empty

    Unless otherwise stated - all code posted by me is untested - I will have to add that to me signature

    Ty for pointing it out
    Tony - Happy to try to help.
    Unless otherwise stated - all code posted by me is untested. Remember to Mark the Thread as Solved.
    Ubuntu user number # 24044 Projects : TimeWarp - on the fly Backups

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •