Is there a better way to check if a dir is empty than parsing it?
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.
The dir() function returns an instance of the Directory class. This function is used to read a directory, which includes the following: The given directory is opened. The two properties handle and path of dir() are available. Both handle and path properties have three methods: read(), rewind(), and close()
The file_exists() function accepts a filename and returns true if the file exists; otherwise it returns false . Note that the $filename can be also a path to a directory. In this case, the file_exists() function returns true if the directory exists.
PHP empty() FunctionThe empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.
Don't think so. Shortest/quickest way I can think of is the following, which should work as far as I can see.
function dir_is_empty($path)
{
$empty = true;
$dir = opendir($path);
while($file = readdir($dir))
{
if($file != '.' && $file != '..')
{
$empty = false;
break;
}
}
closedir($dir);
return $empty;
}
This should only go through a maximum of 3 files. The two .
and ..
and potentially whatever comes next. If something comes next, it's not empty, and if not, well then it's empty.
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