I have directory like:
myproject/
├─ data/
│ ├─ test.csv
├─ go.mod
├─ main.go
package main
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
fullPath := `C:\myproject\data\test.csv`
f, err := os.Open(fullPath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
fileInfo, err := f.Stat()
if err != nil {
log.Fatal(err)
}
// get full file path
filePath, err := filepath.Abs(fileInfo.Name())
if err != nil {
log.Fatal(err)
}
fmt.Println(filePath)
}
However, filepath.Abs(fileInfo.Name())
gives me C:\myproject\test.csv
. instead of what I would desire C:\myproject\data\test.csv
IIUC, fileInfo.Name()
should give me the same path as what was fed into os.Open()
, so why wouldn't filepath.Abs()
recognize the directory that the file is in? filepath.Dir(fileInfo.Name())
gives me .
as well... which I would expect to be C:\myproject\data\
.
I am running my go file from within myproject
directory.
go version 1.19.3 windows/amd64
fileInfo.Name()
returns just the base name of the file, as documented, with no path info. So you're passing just a raw filename to filepath.Abs
. As such, the function is doing exactly what the documentation says it will do:
If the path is not absolute it will be joined with the current working directory to turn it into an absolute path.