List directory in Go

前端 未结 6 738
夕颜
夕颜 2020-12-07 07:37

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 aut

6条回答
  •  旧时难觅i
    2020-12-07 08:16

    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())
        }
    }
    

提交回复
热议问题