83

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?

4

11 Answers 11

88

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.

Note that os.listdir(dir_name) does not include the special entries '.' and '..' even if they are present in the directory.

Source: http://web.archive.org/web/20180531030548/http://thispointer.com/python-how-to-check-if-a-directory-is-empty

3
  • 1
    Found this answer almost verbatim at: 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
    Commented Jan 25, 2022 at 15:45
  • @Rimov you are right. First, I agree that these two codes are copied. Yes, the methods are similar, but the code structure and details (and even the answer structure) are very distinctive for a programmer. Usually small one-time sites copy code from StackOverflow, but this proves another case, because... Second: the article was published on April 15, 2018, which can be seen from the Web Archive (web.archive.org/web/20180531030548/http://thispointer.com/…). I think it will be right to add this article link (or an older article?) as the source. Commented Jun 18, 2022 at 12:02
  • os.path.isdir(dir_name) returning False may also mean dir_name is a file
    – Nolan
    Commented Sep 26, 2023 at 12:24
44

Since Python 3.5+,

with os.scandir(path) as it:
    if any(it):
        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.

6
  • 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.
    – ingyhere
    Commented Mar 4, 2021 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, 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
    Commented Mar 6, 2021 at 0:07
  • 3
    Tip: scandir throws exception if directory doesn't exist so include os.path.isdir check. Commented Sep 29, 2021 at 18:27
  • 1
    I'd like to add that if you don't exit right after this check, it would be good to close the scandir iterator. This is recommended in the official docs: docs.python.org/3/library/os.html#os.scandir (and they say a warning will be raised without that). Commented Jun 18, 2022 at 16:38
  • 4
    @YaroslavNikitenko with does the equivalent thing and is also recommended in the official docs that you link
    – Flair
    Commented Sep 29, 2022 at 15:54
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"
1
11

As mentioned by muskaya here. You can also use pathlib since Python 3.4 (standard lib). 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"
7

Give a try to:

import os
dirContents = os.listdir(downloadsFolder)
if not dirContents:
    print('Folder is Empty')
else:
    print('Folder is Not Empty')
1
4

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
    """
    try:
        if any(scandir(dir_name)):
            return True
    except (NotADirectoryError, FileNotFoundError):
        pass
    return False
5
  • Your answer seems more complex, than other answers. Why would you use a for loop ? Commented Dec 9, 2021 at 8:55
  • I revised my answer upon discovering that Pathlib internally uses os.scandir
    – MusKaya
    Commented Feb 7, 2022 at 19:09
  • I'm afraid this won't capture all errors. I would rather catch OSError (both NotADirectoryError and FileNotFoundError) subclass that. Unfortunately, os.scandir doesn't guarantee that it will raise only OSError-s - however, it is implied in docs.python.org/3/library/os.html#os.walk docs, so that would be safe enough to catch OSError. And if you omitted your variable success and return in place, you could save several lines. Commented Jun 18, 2022 at 16:48
  • However, I think that to assume that the directory is a real directory (not a file) would be cleaner. Two separate concepts "is a directory" and "is empty" are rather different for me (even if one requires the other). I think that a test if is_directory(path) and is_empty_directory(path) looks more explicit (and thus Pythonic). Because otherwise someone might think "not an empty directory => a directory with content", which is wrong. Also, if you call it starting with is_, the bool type hint might be redundant (at least for a programmer, not an automatic tool). Hope this might be helpful! Commented Jun 18, 2022 at 16:56
  • Thanks Yaroslav, I am hesitant to catch a general OSError to be able to highlight any other OS errors that may arise :)
    – MusKaya
    Commented Aug 31, 2022 at 18:04
1

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')
1

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()
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")
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
-5

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 not os.listdir(path): 
    print "Empty" 
else: 
    print "Not empty"  

Hope this is what you're looking for.

1
  • You don't have to compare a dictionary to an empty dictionary: you can just write if not os.listdir(path): instead. Otherwise I can't see how this answer differs from a later answer with 8 votes. stackoverflow.com/a/54034774/952234 Commented Jun 18, 2022 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.