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

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

PHPz
Release: 2024-02-10 16:00:14
forward
949 people have browsed it

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
Copy after login
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)
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template