patterngoCritical
List directory in Go
Viewed 0 times
directoryliststackoverflow
Problem
I've been trying to figure out how to simply list the files and folders in a single directory in Go.
I've found
I'm sure that this functionality exists, but it's been really hard to find. Let me know if anyone knows where I should look. Thanks.
I've found
filepath.Walk, but it goes into sub-directories automatically, which I don't want. All of my other searches haven't turned anything better up. I'm sure that this functionality exists, but it's been really hard to find. Let me know if anyone knows where I should look. Thanks.
Solution
You can try using the ReadDir function in the
ReadDir reads the named directory, returning all its directory entries sorted by filename.
The resulting slice contains
os package. Per the docs:ReadDir reads the named directory, returning all its directory entries sorted by filename.
The resulting slice contains
os.DirEntry types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir() method):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())
}
}Code Snippets
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())
}
}Context
Stack Overflow Q#14668850, score: 510
Revisions (0)
No revisions yet.