Home
Go
Sort by File Size
This page was last reviewed on Nov 17, 2023.
Dot Net Perls
Sort files, size. 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.
ReadDir
Detail Consider the ByFileSize custom sorting type. It implements 3 methods from the sort interface.
sort Slice
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.