Golang Sort by File SizeSort the files in a directory by their size from high to lower, or low to high, using a special sort type.
dot net perls
Sort files. In Go programs we sometimes want to act upon the largest files first, and then proceed to the smallest ones. The opposite order is sometimes desired as well.
Custom sort type. We can use the "sort" package, and call "sort.Sort" on the FileInfo array returned by Readdir. With some custom logic, we can implement our sorting logic.
In this example, we specify a directory and assign this path to the "folder" variable. Then we use os.Open and Readdir to get the list of files in that directory.
ByFileSize Consider the ByFileSize custom sorting type. It implements 3 methods from the sort interface.
And ByFileSize receives a FileInfo array, and sorts each element (in Less) by the return value of Size().
Tip To use an ascending (low to high) sort, change the "greater than" in Less to a "less than" sign.
Golang program that sorts files by size descending
package main import ( "fmt" "os" "sort" "io/fs" ) // Access Size() in Less() to sort by file size. type ByFileSize []fs.FileInfo func (a ByFileSize) Len() int { return len(a) } func (a ByFileSize) Less(i, j int) bool { return a[i].Size() > a[j].Size() } func (a ByFileSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func main() { folder := "/Users/sam/programs/" // Read directory. dirRead, _ := os.Open(folder) dirFiles, _ := dirRead.Readdir(0) // Sort by file size. sort.Sort(ByFileSize(dirFiles)) // Write results. for dirIndex := range dirFiles { fileHere := dirFiles[dirIndex] fmt.Println(fileHere.Name(), fileHere.Size()) } }
search-perls.txt 204568 merged-perls.txt 49157 ... program.php 196
Originally I wrote the file size sorting method to call os.Size on each string file name from a slice. This is inefficient, as the size is already available through FileInfo.
And We can sort on the FileInfo array directly, avoiding further accesses to the operating system.
Sorting files by their size (particularly in descending, low to high order) has been a recurring task in programming. A file's size can indicate its importance.
© 2007-2021 sam allen. see site info on the changelog