Home >Backend Development >Golang >How Can I Efficiently List a Directory's Contents in Go?
Efficiently List Directory Contents in Go
Programmers often encounter the need to list files and folders within a specific directory in Go. However, navigating the package environment can be challenging. This article addresses this requirement and provides a solution.
The filepath.Walk function, while useful, may not be the best option for listing directory contents without delving into subdirectories. The solution lies in the os package and the ReadDir function.
As described in the official documentation, ReadDir "reads the named directory, returning all its directory entries sorted by filename." The result is a slice of os.DirEntry types.
Here's a simple example that utilizes the ReadDir function:
package main import ( "fmt" "os" "log" ) func main() { entries, err := os.ReadDir("./") if err != nil { log.Fatal(err) } for _, e := range entries { fmt.Println(e.Name()) } }
This code traverses the current directory and prints the names of all entries, including both files and folders. Note that folders are not specifically marked. To distinguish between the two, you can utilize the IsDir() method provided by the os.DirEntry type.
The above is the detailed content of How Can I Efficiently List a Directory's Contents in Go?. For more information, please follow other related articles on the PHP Chinese website!