Logo

Programming-Idioms

  • JS
  • Ruby
  • Python
  • Go
  • Elixir

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
b = Dir.empty?(p)

Returns true if the named file is an empty directory, false if it is not a directory or non-empty.
import os
b = os.listdir(p) == []
import "os"
dir, err := os.Open(p)
if err != nil {
	panic(err)
}
defer dir.Close()
_, err = dir.Readdirnames(1)
b := err == io.EOF

Error may happen, and should be dealt with.

b is set to true if EOF was encountered before reading 1 contained file name.
import 'dart:io';
var b = await Directory(p).list().isEmpty;

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