Golang gets the list of files under the folder

golang document it is easier to find a method is filepath. Walk, this method has a problem of the current directory is automatically recursive traversal subdirectory, in fact, we usually just want to get a directory file list below, does not need so much information, at the same time this method is much more complicated to write code, we have no need to do so.

if you simply want to get a list of files and folders under a directory, there are two easy ways to do

USES ioutil’s ReadDir method

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    files, _ := ioutil.ReadDir("./")
    for _, f := range files {
            fmt.Println(f.Name())
    }
}

using filepath Glob method

package main    

import (
    "fmt"
    "path/filepath"
)

func main() {
    files, _ := filepath.Glob("*")
    fmt.Println(files) // contains a list of all files in the current directory
}

Read More: