How do you get full paths of all files in a directory in Go?

You can also use the filepath.Abs method from the standard library

import (
    "fmt"
    "os"
    "path/filepath"
)

files, _ = os.ReadDir(dir)
path, _ := filepath.Abs(dir)
for _, file := range files {
    fmt.Println(filepath.Join(path, file.Name())
}

If you want to see a full path, you should start with a full path. . is a relative path.

You can get the working path with os.Getwd

path, err := os.Getwd()
// handle err
printFiles(path)

The rest is simply appending the file name to the directory path. You should use the path/filepath package for that:

for _, file := range fileInfos {
    fmt.Println(filepath.Join(path, file.Name())
}

Tags:

Go