[Golang] Remove Empty Directory


Given a directory, remove all empty sub-directories in Go. We use filepath.Walk to find all directories and ioutil.ReadDir to check if a directory is empty. Then use os.Remove to remove the directory if the directory is empty.

package main

import (
      "flag"
      "fmt"
      "io/ioutil"
      "os"
      "path/filepath"
)

func processDir(path string, info os.FileInfo) {
      files, err := ioutil.ReadDir(path)
      if err != nil {
              panic(err)
      }

      if len(files) != 0 {
              return
      }

      err = os.Remove(path)
      if err != nil {
              panic(err)
      }

      fmt.Println(path, "removed!")
}

func main() {
      root := flag.String("root", "Instagram", "dir of downloaded files")
      flag.Parse()

      err := filepath.Walk(*root, func(path string, info os.FileInfo, err error) error {
              if err != nil {
                      fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
                      return err
              }
              if info.IsDir() {
                      processDir(path, info)
              }

              return nil
      })
      if err != nil {
              panic(err)
              return
      }
}

References:

[1][Golang] Parse Command Line Arguments - String Variable
[2][Golang] Walk All Files in Directory