go filepath

func Getwd() (dir string, err error)
Getwd返回一个对应当前工作目录的根路径。

func Abs(path string) (string, error)
Abs函数返回path代表的绝对路径,如果path不是绝对路径,会加入当前工作目录以使之成为绝对路径。

func Split(path string) (dir, file string)
Split函数将路径从最后一个路径分隔符后面位置分隔为两个部分(dir和file)并返回。如果路径中没有路径分隔符,函数返回值dir会设为空字符串,file会设为path。

func Dir(path string) string
Dir返回路径除去最后一个路径元素的部分,即该路径最后一个元素所在的目录。

func Base(path string) string
Base函数返回路径的最后一个元素。即获得文件名

func Ext(path string) string
Ext函数返回path文件扩展名。

package main

import (
    "path/filepath"
    "os"
    "fmt"
)
func main() {
    cur, _ := os.Getwd()
    fmt.Println(cur)

    str := "s.txt"
    path, _ := filepath.Abs(str) //文件默认为当前目录下,返回绝对路径
    fmt.Println(path)

    fmt.Println(filepath.Dir(path))    //获得文件所在的目录
    fmt.Println(filepath.Split(path))  //
    fmt.Println(filepath.Base(path))
    fmt.Println(filepath.Ext(path))
}

cts@cts-pc:~/test/demo$ go run a.go
/home/cts/test/demo
/home/cts/test/demo/s.txt
/home/cts/test/demo
/home/cts/test/demo/ s.txt
s.txt
.txt

posted @ 2021-02-24 14:50  牧 天  阅读(169)  评论(0)    收藏  举报