ReadDir
Consider a directory (a folder). It contains many files—we often we want a list of these files. In the Go language, we must combine 2 methods to get a list of all the files.
With the os package, we have access to many file system functions. We first need os.Open
. We can use ReadDir
(which is faster) or Readdir
(the older method).
To begin, we make sure to import the "os" package. We then invoke os.Open
on the target directory (the one we want to get all the files from).
ReadDir
. The argument 0 is acceptable—this means all files are returned.for-range
loop to iterate over all the files. We call the Name()
func
to get each file's name.package main import ( "fmt" "os" ) func main() { // Directory we want to get all files from. directory := "/Users/sam/"; // Open the directory. outputDirRead, _ := os.Open(directory) // Call ReadDir to get all files. outputDirFiles, _ := outputDirRead.ReadDir(0) // Loop over files. for outputIndex := range(outputDirFiles) { outputFileHere := outputDirFiles[outputIndex] // Get name of file. outputNameHere := outputFileHere.Name() // Print name. fmt.Println(outputNameHere) } }... Downloads .python_history .putty .bash_history .viminfo .zsh_sessions
Readdir
, ReadDir
New releases of Go have the ReadDir
(capitalized Dir) method. This is implemented in a different way—it returns fs.DirEntry
, not fs.FileInfo
.
ReadDir
method is much faster than Readdir
. For a folder with over a thousand files, this can save 4 milliseconds.Readdir
, and one that uses ReadDir
. The timings come after the 2 programs.Readdir
to ReadDir
, the result value changes and some code may need updating if the result is stored anywhere.ReadDir
should always be preferred.package main import ( "fmt" "os" "time" ) func main() { directory := "/Users/sam/perls/t/" outputDirRead, _ := os.Open(directory) t0 := time.Now() outputDirFiles, _ := outputDirRead.Readdir(0) t1 := time.Now() fmt.Println("Time:", t1.Sub(t0), len(outputDirFiles)) }package main import ( "fmt" "os" "time" ) func main() { directory := "/Users/sam/perls/t/" outputDirRead, _ := os.Open(directory) t0 := time.Now() outputDirFiles, _ := outputDirRead.ReadDir(0) t1 := time.Now() fmt.Println("Time:", t1.Sub(t0), len(outputDirFiles)) }Time: 5.764292ms 1607 (Readdir) Time: 1.143333ms 1607 (ReadDir)
This method works on Linux (as the output reveals). But with Windows-style paths, it can also work on a Windows system. The paths are system-dependent.
The os package in Go is powerful, and has methods that can act upon the file system. Often (as with this example) we must combine 2 or more methods.