Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List directory in Go

Tags:

go

I've been trying to figure out how to simply list the files and folders in a single directory in Go.

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.

like image 305
Behram Mistree Avatar asked Feb 03 '13 02:02

Behram Mistree


People also ask

How do I read a directory in go?

You can try using the ReadDir function in the io/ioutil package. Per the docs: ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

How do I search for a directory in Golang?

os. Stat and os. IsNotExist() can be used to check whether a particular file or directory exist or not.


1 Answers

You can try using the ReadDir function in the io/ioutil package. Per the docs:

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

The resulting slice contains os.FileInfo 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"     "io/ioutil"      "log" )  func main() {     files, err := ioutil.ReadDir("./")     if err != nil {         log.Fatal(err)     }       for _, f := range files {             fmt.Println(f.Name())     } } 
like image 127
RocketDonkey Avatar answered Sep 25 '22 01:09

RocketDonkey