Golang operation file traverses directory to obtain file list

The package of the path/filepath standard library provides a convenient Walk method, which can automatically scan subdirectories and is easy to use

package main
import (
    "fmt"
    "os"
    "path/filepath"
)
func main() {
    var files []string
    root := "/some/folder/to/scan"
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        files = append(files, path)
        return nil
    })
    if err != nil {
        panic(err)
    }
    for _, file := range files {
        fmt.Println(file)
    }
}

filepath. Walk is very convenient, but it will scan all subfolders. By default, but sometimes this is not what we want

The standard library of go also provides ioutil. ReadDir

Ioutil. ReadDir requires a string type folder path and then returns a slice of os.FileInfo, as mentioned above.

package main
import (
    "fmt"
    "io/ioutil"
    "log"
)
func main() {
    files, err := ioutil.ReadDir(".")
    if err != nil {
        log.Fatal(err)
    }
    for _, file := range files {
        fmt.Println(file.Name())
    }
}

The internal implementation of ReadDir

// ReadDir reads the directory named by dirname and returns
// a list of directory entries sorted by filename.
func ReadDir(dirname string) ([]os.FileInfo, error) {
    f, err := os.Open(dirname)
    if err != nil {
        return nil, err
    }
    list, err := f.Readdir(-1)
    f.Close()
    if err != nil {
        return nil, err
    }
    sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
    return list, nil
}

We can see that it only scans the folder directory, and then sorts the files by name. If we do not need this sort, we can:

package main
import (
    "fmt"
    "log"
    "os"
)
func main() {
    dirname := "."
    f, err := os.Open(dirname)
    if err != nil {
        log.Fatal(err)
    }
    files, err := f.Readdir(-1)
    f.Close()
    if err != nil {
        log.Fatal(err)
    }
    for _, file := range files {
        fmt.Println(file.Name())
    }
}

Go Get the absolute path of the current project

package main
import (
    "fmt"
    "os"
    "path/filepath"
)
func main() {
    path, err2 := os.Executable()
    if err2 != nil {
        fmt.Println(err2)
    }
    dir := filepath.Dir(path)
    fmt.Println("111", path) // /Users/mac/repose/idphoto_server_lite/test/test3
    fmt.Println("2222", dir) // /Users/mac/repose/idphoto_server_lite/test
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish