Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if folder is empty with Python?

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?

like image 712
sprogissd Avatar asked Mar 14 '18 17:03

sprogissd


People also ask

How do you check if a folder is empty or not in Python?

To check whether a directory is empty or not os. listdir() method is used. os. listdir() method of os module is used to get the list of all the files and directories in the specified directory.

How do you check if a folder is empty or not?

File. list() is used to obtain the list of the files and directories in the specified directory defined by its path name. This list of files is stored in a string array. If the length of this string array is greater than 0, then the specified directory is not empty.

Is directory empty bash?

There are many ways to find out if a directory is empty or not under Linux and Unix bash shell. You can use the find command to list only files. In this example, find command will only print file name from /tmp. If there is no output, directory is empty.


1 Answers

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.

like image 61
Nevzat Günay Avatar answered Sep 19 '22 20:09

Nevzat Günay