日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Golang?filepath包常用函數(shù)詳解_Golang

作者:夢(mèng)想畫家 ? 更新時(shí)間: 2023-04-03 編程語言

絕對(duì)路徑

絕對(duì)路徑時(shí)從根目錄開始的完整路徑,相對(duì)路徑是相對(duì)與當(dāng)前工作目錄的路徑。filepath.Abs 返回文件的絕對(duì)路徑,filepath.IsAbs 可以檢查給定路徑是否為絕對(duì)路徑。請(qǐng)看示例:

package main
import (
    "fmt"
    "log"
    "path/filepath"
)
func main() {
    fname := "./main.go"
    abs_fname, err := filepath.Abs(fname)
    if err != nil {
        log.Fatal(err)
    }
    if filepath.IsAbs(fname) {
        fmt.Printf("%s - is an absolute path\n", fname)
    } else {
        fmt.Printf("%s - is not an absolute path\n", fname)
    }
    if filepath.IsAbs(abs_fname) {
        fmt.Printf("%s - is an absolute path\n", abs_fname)
    } else {
        fmt.Printf("%s - is not an absolute path\n", abs_fname)
    }
}

上述示例使用了filepath.Abs 和 filepath.IsAbs 函數(shù),分別獲取絕對(duì)路徑并判斷給定文件路徑是否為絕對(duì)路徑。

文件名和目錄

filepath.Base函數(shù)返回文件路徑的最后元素,通常為文件名。filepath.Dir返回文件路徑中除了最后元素的部分,通常為文件目錄。

package main
import (
    "fmt"
    "log"
    "path/filepath"
)
func main() {
    p, err := filepath.Abs("./main.go")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(p)
    fmt.Printf("Base: %s\n", filepath.Base(p))
    fmt.Printf("Dir: %s\n", filepath.Dir(p))
}

運(yùn)行程序分別打印出文件名和文件所在目錄。

filepath.Ext

filepath.Ext返回文件路徑中文件的擴(kuò)展名。

package main
import (
    "fmt"
    "path/filepath"
)
func main() {
    p := "/home/user7/media/aliens.mp4"
    ext := filepath.Ext(p)
    fmt.Println("File extension:", ext)
    p = "./main.go"
    ext = filepath.Ext(p)
    fmt.Println("File extension:", ext)
}

運(yùn)行程序,分別返回mp4和go擴(kuò)展名。

最短路徑

filepath.Clean函數(shù)清除重復(fù)和不規(guī)則的文件路徑,通過純?cè)~法處理返回與指定路徑等效的最短路徑名。

package main
import (
    "fmt"
    "path"
)
func main() {
    paths := []string{
        "home/user7",
        "home//user7",
        "home/user7/.",
        "home/user7/Documents/..",
        "/../home/user7",
        "/../home/Documents/../././/user7",
        "",
    }
    for _, p := range paths {
        fmt.Printf("%q = %q\n", p, path.Clean(p))
    }
}

運(yùn)行程序輸出結(jié)果為:

$ go run main.go
"home/user7" = "home/user7"
"home//user7" = "home/user7"
"home/user7/." = "home/user7"
"home/user7/Documents/.." = "home/user7"
"/../home/user7" = "/home/user7"
"/../home/Documents/../././/user7" = "/home/user7"
"" = "."

路徑分割

filepath.Split函數(shù)分割給定路徑為目錄和文件組件,filepath.SplitList函數(shù)分割一組由OS指定分隔符的連接字符串生成字符串切片。

package main
import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)
func main() {
    cwd, err := os.Getwd()
    if err != nil {
        log.Fatal(err)
    }
    dir, file := filepath.Split(cwd)
    fmt.Printf("Directory: %s\n", dir)
    fmt.Printf("File: %s\n", file)
    home, err := os.UserHomeDir()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("-------------------------")
    dir, file = filepath.Split(home)
    fmt.Printf("Directory: %s\n", dir)
    fmt.Printf("File: %s\n", file)
    path_env := os.Getenv("PATH")
    paths := filepath.SplitList(path_env)
    for _, p := range paths {
        fmt.Println(p)
    }
}

上例中首先分割當(dāng)前工作目錄和用戶主目錄,然后把path變量的一組路徑分割為切片。

文件遍歷

filepath.Walk函數(shù)在根目錄下遍歷文件樹。函數(shù)簽名為:

func Walk(root string, fn WalkFunc) error

遍歷目錄樹下每個(gè)文件或目錄,包括root目錄。

package main
import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)
func main() {
    var files []string
    root := "/home/jano/Documents"
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            fmt.Println(err)
            return nil
        }
        if !info.IsDir() && filepath.Ext(path) == ".txt" {
            files = append(files, path)
        }
        return nil
    })
    if err != nil {
        log.Fatal(err)
    }
    for _, file := range files {
        fmt.Println(file)
    }
}

上面示例遍歷Document目錄下文件,列舉所有文本文件(擴(kuò)展名為txt的文件)。

文件名匹配

filepath.Glob函數(shù)返回模式匹配的文件名,不匹配則返回nil。函數(shù)簽名如下:

func Glob(pattern string) (matches []string, err error)

請(qǐng)下面示例代碼:

package main
import (
    "fmt"
    "log"
    "path/filepath"
)
func main() {
    files, err := filepath.Glob("/home/jano/Documents/prog/go/**/**/*.go")
    fmt.Println(len(files))
    if err != nil {
        log.Fatal(err)
    }
    for _, file := range files {
        fmt.Println(file)
    }
}

上面示例列舉給定目錄下所有g(shù)o文件,**模式表示遞歸列舉。其他模式格式為:

pattern:
?? ?{ term }
term:
?? ?'*' ? ? ? ? matches any sequence of non-Separator characters
?? ?'?' ? ? ? ? matches any single non-Separator character
?? ?'[' [ '^' ] { character-range } ']'
?? ? ? ? ? ? ? ?character class (must be non-empty)
?? ?c ? ? ? ? ? matches character c (c != '*', '?', '\\', '[')
?? ?'\\' c ? ? ?matches character c

character-range:
?? ?c ? ? ? ? ? matches character c (c != '\\', '-', ']')
?? ?'\\' c ? ? ?matches character c
?? ?lo '-' hi ? matches character c for lo <= c <= hi

filepath.VolumeName

filepath.VolumeName函數(shù)基于文件路徑返回windows前導(dǎo)卷名稱,其他平臺(tái)返回空字符串。舉例:給定"C:\foo\bar" 在 Windows平臺(tái)返回 “C:”。 給定 “\host\share\foo” 返回 “\host\share”。其他平臺(tái)返回 “”。

請(qǐng)看示例:

package main
import (
    "fmt"
    "log"
    "path/filepath"
)
func main() {
    fname := "./main.go"
    ap, err := filepath.Abs(fname)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(filepath.VolumeName(ap))
}

原文鏈接:https://blog.csdn.net/neweastsun/article/details/128792296

欄目分類
最近更新