List Directory in Go

I tried to figure out how easy it is to list files and folders in the same directory in Go.

I found filepath.Walk , but it automatically gets into subdirectories, which I don't want. All my other searches have not improved.

I am sure that this functionality exists, but it was very difficult to find. Let me know if anyone knows where I should look. Thank.

+74
go
Feb 03 '13 at 2:17
source share
3 answers

You can try using ReadDir in the io/ioutil . In documents:

ReadDir reads a directory named dirname and returns a list of sorted directory entries.

The resulting snippet contains the os.FileInfo types that provide the methods listed below 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 the item is a folder using the IsDir() method):

 package main import ( "fmt" "io/ioutil" "log" ) func main() { files, err := ioutil.ReadDir("./") if err != nil { log.Fatal(err) } for _, f := range files { fmt.Println(f.Name()) } } 
+160
Feb 03 '13 at 2:29
source share

Even simpler, use path/filepath :

 package main import ( "fmt" "log" "path/filepath" ) func main() { files, err := filepath.Glob("*") if err != nil { log.Fatal(err) } fmt.Println(files) // contains a list of all files in the current directory } 
+41
Aug 20 '13 at 7:04 on
source share

ioutil.ReadDir is a good find, but if you click and look at the source, you will see that it calls the Readdir of os.File method . If you agree with the order of the directories and don’t need to sort the list, then you need this Readdir method.

+16
03 Feb '13 at 11:58
source share



All Articles