[Golang] Sort Files by Size


Sort files in a directory by size in Go. The steps are:

  1. Use ioutil.ReadDir to get files in a directory (not including sub-directories).
  2. Use sort.Slice to sort the files by size.

The following are complete source code.

sortfile.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Sort file by size
package sortfile

import (
	"os"
	"sort"
)

func SortFileBySize(files []os.FileInfo) {
	sort.Slice(files, func(i, j int) bool {
		return files[i].Size() < files[j].Size()
	})
}
sortfile_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package sortfile

import (
	"fmt"
	"io/ioutil"
	"os"
	"testing"
)

func ExampleSortFileBySize(t *testing.T) {
	files, err := ioutil.ReadDir(os.Getenv("MY_DIR"))
	if err != nil {
		panic(err)
	}
	SortFileBySize(files)
	for _, file := range files {
		fmt.Println(file.Name()+": ", file.Size())
	}
}

If you want to know how to sort prior to Go 1.8, see [1].

If you want to find all files in a directory and all its sub-directories, see [2].

Tested on:

  • Ubuntu Linux 17.10, Go 1.9.4

References:

[1][Golang] Sort String by Character
[2][Golang] Walk All Files in Directory