Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #273 Check if folder is empty

Set the boolean b to true if the directory at filepath p is empty (i.e. doesn't contain any other files and directories)

def main(p) do
  b = File.ls!(p) == []
end
import 'dart:io';
var b = await Directory(p).list().isEmpty;
import "os"
dir, err := os.Open(p)
if err != nil {
	panic(err)
}
defer dir.Close()
_, err = dir.Readdirnames(1)
b := err == io.EOF
boolean b = p.list().length == 0;
(let ((b (directory p)))
  (if (null b) t nil))
$iterator = new FilesystemIterator($p, FilesystemIterator::SKIP_DOTS);
$b = (iterator_count($iterator) === 0);
uses FileUtil;
with FindAllFiles(p, AllFilesMask, False) do
try
  b := DirectoryExists(p) and (Count = 0);
finally
  Free;
end;
opendir(my $dh, $p) || die($!);
my $b = scalar(grep { !/^[\.]{1,2}$/ } readdir($dh)) ? 1 : 0;
closedir($dh);
import os
b = os.listdir(p) == []
b = Dir.empty?(p)
use std::fs;
let b = fs::read_dir(p).unwrap().count() == 0;

New implementation...
< >
programming-idioms.org