Home
Go
Sort by File Size
Updated 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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 17, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen