[Golang] Delete Zero Size Files in Directory
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 |