2

Suppose I have a directory C:/Test that is either empty or contains more than 2000000 files, all with the same extension (e.g. *.txt).

How can I use Python to determine if the directory is empty WITHOUT the enumeration of files?

TheCodeArtist
  • 20,467
  • 4
  • 64
  • 128
Birdy40
  • 327
  • 1
  • 6
  • 13
  • Here is the answer that you're looking for : http://stackoverflow.com/questions/6215334/finding-empty-directories-in-python – mihau Aug 06 '14 at 23:38
  • This is an interesting approach (using rmdir); but, I really do not wish to remove the directory when it is empty. I just wish to know if it is or is not empty --- that's all. – Birdy40 Aug 06 '14 at 23:49

2 Answers2

9

I realise this is quite an old question but I found this as I was looking to do a similar thing and I found os.scandir to be useful in combination with any(). scandir() will return an iterator of entries in a directory rather than a list. any() can evaluate if the iterator is non-empty.

for _ in os.scandir(path):
 print('not empty')
 break

or

if any(os.scandir(path)):
   print('not empty')
Andy White
  • 368
  • 3
  • 6
3

Is this what you're looking for?

import os
if not os.listdir('C:/Test'):
    print "empty"

edit: test run

for x in range(0, 3000000):
    open(str(x), 'a').close()

print not os.listdir('.')

output: False

rocktheartsm4l
  • 2,079
  • 19
  • 36
  • 1
    I don't believe this will handle a directory that contains a very large number of files. – Birdy40 Aug 06 '14 at 23:43
  • @user1435385 I'm not sure what you mean by "a very number of files." This code will tell you if a directory is empty -- as far as I know it doesn't matter what files are in the directory. Did you mean, "A very large number of files?" If so then you may be correct cause I haven't tried that. – rocktheartsm4l Aug 06 '14 at 23:46
  • @user1435385 ahhh. I replied to fast that is what you meant! – rocktheartsm4l Aug 06 '14 at 23:47
  • @user1435385 I just created a directory with 3,000,000 files and this code functioned properly. – rocktheartsm4l Aug 07 '14 at 00:01
  • This works ok for my purposes @rocktheartsm41. However, there may be a more general approach for getting information on directories in Windows (e.g. their size) when python 3.5 is released :-). – Birdy40 Aug 09 '14 at 08:39