4

[Golang] Delete Zero Size Files in Directory

 2 years ago
source link: http://siongui.github.io/2018/05/10/go-delete-zero-size-file-in-folder/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Delete Zero Size Files in Directory

May 10, 2018

Find all files with size = 0 in the directory recursively. First we use filepath.Walk to recursively find all files in the directory, sub-directories included. Then we check the file size and if it is zero, call os.Remove to delete the file.

import (
      "fmt"
      "os"
      "path/filepath"
)

func DeleteZeroSizeFile(dir string) error {
      return filepath.Walk(dir, func(path string, info os.FileInfo, e error) error {
              if e != nil {
                      return e
              }

              if info.Mode().IsRegular() && info.Size() == 0 {
                      fmt.Println("Removing", path)
                      os.Remove(path)
              }
              return nil
      })
}

If you do not want to walk into sub-directories, use ioutil.ReadDir.


Tested on: Ubuntu Linux 18.04, Go 1.10.2.

References:

[1]func Walk - filepath - The Go Programming Language

[2]func ReadDir - ioutil - The Go Programming Language


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK