Home  >  Article  >  Backend Development  >  filepath.Abs​() does not provide subdirectories in results

filepath.Abs​() does not provide subdirectories in results

PHPz
PHPzforward
2024-02-10 16:00:14908browse

filepath.Abs​​() 在结果中不提供子目录

php editor Yuzai introduced a useful function related to file paths: filepath.Abs(). This function will not include subdirectories when returning results. This function is very useful for developers who need to obtain the absolute path of a file but do not need subdirectory information. By using the filepath.Abs() function, developers can easily obtain the absolute path of a file without worrying about interference from subdirectory information. The simplicity and practicality of this function make it one of the preferred tools for PHP developers.

Question content

I have a directory like this:

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

But, filepath.Abs​​(fileInfo.Name()) gives me C:\myproject\test.csv. Instead of what I want C:\myproject\data\test.csv

IIUC, fileInfo.Name() should give me the same path as the input os.Open(), so why filepath.Abs​​() What if the directory where the file is located cannot be identified? filepath.Dir(fileInfo.Name()) also gives me . ...which I hope is C:\myproject\data\.

I'm running my go file in the myproject directory.

go version 1.19.3 windows/amd64

Solution

fileInfo.Name() Returns only the base name of the file, As stated in the documentation a>, there is no path information. So you just pass the original filename to filepath.Abs​. So the function is doing exactly what the documentation says : p>

The above is the detailed content of filepath.Abs​() does not provide subdirectories in results. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete