67

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,755
  • 5
  • 24
  • 45

11 Answers11

76

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

Agostino
  • 2,723
  • 9
  • 48
  • 65
Nevzat Günay
  • 1,039
  • 11
  • 19
  • 1
    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
  • @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 (http://web.archive.org/web/20180531030548/http://thispointer.com/python-how-to-check-if-a-directory-is-empty). I think it will be right to add this article link (or an older article?) as the source. – Yaroslav Nikitenko Jun 18 '22 at 12:02
39

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.

Flair
  • 2,609
  • 1
  • 29
  • 41
  • 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
  • 3
    Tip: `scandir` throws exception if directory doesn't exist so include `os.path.isdir` check. – Shital Shah Sep 29 '21 at 18:27
  • Thank you! Even though `scandir` provides additional information to `listdir`, it still runs faster even for the whole directory (as I understand from this answer, https://stackoverflow.com/questions/59268696/why-is-os-scandir-as-slow-as-os-listdir). Of course, it will run even faster if it doesn't need to scan everything. – Yaroslav Nikitenko Jun 18 '22 at 12:23
  • 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: https://docs.python.org/3/library/os.html#os.scandir (and they say a warning will be raised without that). – Yaroslav Nikitenko Jun 18 '22 at 16:38
  • 3
    @YaroslavNikitenko `with` does the equivalent thing and is also recommended in the official docs that you link – Flair Sep 29 '22 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"
algrice
  • 229
  • 1
  • 4
  • https://docs.python.org/3/library/os.html#os.listdir listdir() doesn't include . or .. This code ignores the presence of hidden files, e.g. .gitignore, which is inconsistent with what I would call an empty directory. – neuralmer Aug 04 '22 at 18:47
9

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"
Rene
  • 976
  • 1
  • 13
  • 25
7

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
  • 137,073
  • 23
  • 153
  • 219
sspsujit
  • 301
  • 4
  • 12
3

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
MusKaya
  • 41
  • 5
  • Your answer seems more complex, than other answers. Why would you use a for loop ? – Emmanuel-Lin Dec 09 '21 at 08:55
  • I revised my answer upon discovering that Pathlib internally uses os.scandir – MusKaya Feb 07 '22 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 https://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. – Yaroslav Nikitenko Jun 18 '22 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! – Yaroslav Nikitenko Jun 18 '22 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 Aug 31 '22 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()
Dharman
  • 30,962
  • 25
  • 85
  • 135
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.
  • 3,784
  • 25
  • 28
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
  • 5,974
  • 9
  • 37
  • 87
-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.

Yaroslav Nikitenko
  • 1,695
  • 2
  • 23
  • 31
Rob G
  • 21
  • 3
  • 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. https://stackoverflow.com/a/54034774/952234 – Yaroslav Nikitenko Jun 18 '22 at 12:15