Golang Readdir Example (Get All Files in Directory)Get all the files in a directory with os.Open and the Readdir func. Loop over the files with a for-loop.
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. The Readdir() method (no capital letter on Dir) can be called on a file.
An example. 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 This is an important step—we must call Readdir. The argument 0 is acceptable—this means no options are applied in the operation.
For We use a for-range loop to iterate over all the files. We call the Name() func to get each file's name.
Finally We can get the full path for each file by using the directory we are reading from, and prepending that to the file's name.
Golang program that uses Readdir
package main import ( "fmt" "os" ) func main() { // Directory we want to get all files from. directory := "/home/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) } }
.config .xsession-errors.old Downloads .profile Templates coin.jpg test.py .xsession-errors examples.desktop .ICEauthority .pki .bash_logout .local .Xauthority .bash_history Documents .compiz .bashrc Pictures Link to firefox-bin .sudo_as_admin_successful .gnupg .mozilla test .dbus .cache program.go Videos Public .gconf Desktop Music
Notes, Linux. 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.
A review. 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.
© 2007-2021 sam allen. see site info on the changelog