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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With