48

I am trying to check if a folder is empty and do the following:

import os
downloadsFolder = '../../Downloads/'
if not os.listdir(downloadsFolder):
    print "empty"
else:
    print "not empty"

Unfortunately, I always get "not empty" no matter if I have any files in that folder or not. Is it because there might be some hidden system files? Is there a way to modify the above code to check just for not hidden files?

sprogissd
  • 2,225
  • 5
  • 20
  • 38

11 Answers11

52

You can use these two methods from the os module.

First option:

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")

Second option (as an empty list evaluates to False in Python):

import os
if not os.listdir('/your/path'):
    print("Directory is empty")
else:    
    print("Directory is not empty")

However, the os.listdir() can throw an exception, for example when the given path does not exist. Therefore, you need to cover this.

import os
dir_name = '/your/path'
if os.path.isdir(dir_name):
    if not os.listdir(dir_name):
        print("Directory is empty")
    else:    
        print("Directory is not empty")
else:
    print("Given directory doesn't exist")

I hope it will be helpful for you.

Nathan Reed
  • 3,235
  • 1
  • 23
  • 31
Nevzat Günay
  • 773
  • 9
  • 19
  • Found this answer almost verbatim at: https://thispointer.com/python-how-to-check-if-a-directory-is-empty/ . Couldn't find the published date of the article so cannot judge one way or the other – Rimov Jan 25 '22 at 15:45
  • Hey Rimov, When I wrote the answer, I was working on saving and ordering the folders and their files for analyzing in Python. At that time, I saw the question and just have shared my code block here. I have no idea about the article, but there are fundamental methods/approaches for handling folder/file checking in Python, so you can see similar codes on the Internet. – Nevzat Günay Jan 26 '22 at 07:28
25

Since Python 3.5+,

if any(os.scandir(path)):
   print('not empty')

which generally performs faster than listdir() since scandir() is an iterator and does not use certain functions to get stats on a given file.

Flair
  • 2,123
  • 1
  • 24
  • 39
  • 1
    There is also `Path.iterdir()` but that uses `listdir()` under the covers, so slower, maybe. Sometimes, if your directory structure is large, you'll want `iterdir()` instead of `scandir()` because `scandir()` can be [resource intensive with file descriptors](https://bugs.python.org/issue39907). – ingyhere Mar 04 '21 at 23:15
  • @ingyhere so the difference in the performance you see there and the general `scandir()` vs `listdir()` is that `list(scandir())` is being used instead of `scandir()` itself. Depending on how many files you go through and what you do with them, `scandir()` and `listdir()` may or may not be better for you. For instance, https://bugs.python.org/issue23605. OP here just needs to know if there is at least 1 file in directory, so `scandir()` is just going to be faster. – Flair Mar 06 '21 at 00:07
  • 1
    Tip: `scandir` throws exception if directory doesn't exist so include `os.path.isdir` check. – Shital Shah Sep 29 '21 at 18:27
19

Hmm, I just tried your code changing the path to an empty directory and it did print "empty" for me, so there must be hidden files in your downloads. You could try looping through all files and checking if they start with '.' or not.

EDIT:

Try this. It worked for me.

if [f for f in os.listdir(downloadsFolder) if not f.startswith('.')] == []:
    print "empty"
else: 
    print "not empty"
algrice
  • 229
  • 1
  • 4
8

Give a try to:

import os
dirContents = os.listdir(downloadsFolder)
if not dirContents:
    print('Folder is Empty')
else:
    print('Folder is Not Empty')
Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
sspsujit
  • 293
  • 4
  • 11
3

As mentioned by muskaya here. You can also use pathlib. However, if you only want to check, if the folder is empty or not, you should check out this answser:

from pathlib import Path

def directory_is_empty(directory: str) -> bool:
    return not any(Path(directory).iterdir())


downloadsFolder = '../../Downloads/'
if directory_is_empty(downloadsFolder):
    print "empty"
else:
    print "not empty"
Rene
  • 619
  • 1
  • 8
  • 22
2

expanding @Flair's answer with error handling:

you can use os.scandir:

from os import scandir


def is_non_empty_dir(dir_name: str) -> bool:
    """
    Returns True if the directory exists and contains item(s) else False
    """
    success = False
    try:
        if any(scandir(dir_name)):
            success = True
    except NotADirectoryError:
        pass
    except FileNotFoundError:
        pass
    return success
MusKaya
  • 31
  • 4
0

I think you can try this code:

directory = r'path to the directory'

from os import walk

f = [] #to list the files

d = [] # to list the directories


for (dirpath, dirnames, filenames) in walk(directory):

    f.extend(filenames)
    d.extend(dirnames)
    break

if len(f) and len(d) != 0:
    print('Not empty')
else:
    print('empty')
0

Yet another version:

def is_folder_empty(dir_name):
    import os
    if os.path.exists(dir_name) and os.path.isdir(dir_name):
        return not os.listdir(dir_name)
    else:
        raise Exception(f"Given output directory {dir_name} doesn't exist")
Tomas G.
  • 2,911
  • 19
  • 23
0

You can use the following to validate that no files exist inside the input folder:

import glob

if len(glob.glob("input\*")) == 0:
    print("No files found to Process...")
    exit()
Dharman
  • 26,923
  • 21
  • 73
  • 125
0

TLDR ( for python 3.10.4 ): if not os.listdir(dirname): ...

Here is a quick demo:

$ rm -rf BBB
$ mkdir BBB
$ echo -e "import os\nif os.listdir(\"BBB\"):\n  print(\"non-empty\")\nelse:\n  print(\"empty\")" > empty.py
$ python empty.py
empty
$ echo "lorem ipsum" > BBB/some_file.txt
$ python empty.py
non-empty
$ rm BBB/some_file.txt 
$ python empty.py
empty
OrenIshShalom
  • 4,294
  • 5
  • 22
  • 55
-6

In python os, there is a function called listdir, which returns an array of the files contents of the given directory. So if the array is empty, it means there are no files in the directory.

Here is a code snippet;

import os 
path = '../../Downloads' 
if os.listdir(path) == []: 
    print "Empty" 
else: 
    print "Not empty"  

Hope this is what you're looking for.

Rob G
  • 11
  • 3