File Paths {.en}

文件路径 {.zh}

::: {.en} The filepath package provides functions to parse and construct file paths in a way that is portable between operating systems; dir/file on Linux vs. dirfile on Windows, for example. :::

::: {.zh}

filepath包提供了以可在操作系统之间移植的方式解析和构造文件路径的函数;例如,Windows上的dir / file和Windows上的.dirfile`。

:::

  1. package main
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. )
  7. func main() {

::: {.en} Join should be used to construct paths in a portable way. It takes any number of arguments and constructs a hierarchical path from them. :::

::: {.zh}

Join应该用于以便携方式构造路径。它接受任意数量的参数并从中构造分层路径。

:::

  1. p := filepath.Join("dir1", "dir2", "filename")
  2. fmt.Println("p:", p)

::: {.en} You should always use Join instead of concatenating /s or `s manually. In addition to providing portability,Join` will also normalize paths by removing superfluous separators and directory changes. :::

::: {.zh}

你应该总是使用Join而不是手动连接/s或s。除了提供可移植性之外,Join`还会通过删除多余的分隔符和目录更改来对路径进行alsonormal化。

:::

  1. fmt.Println(filepath.Join("dir1//", "filename"))
  2. fmt.Println(filepath.Join("dir1/../dir1", "filename"))

::: {.en} Dir and Base can be used to split a path to the directory and the file. Alternatively, Split will return both in the same call. :::

::: {.zh}

DirBase可用于分割目录和文件的路径。或者,Split将在同一个调用中返回。

:::

  1. fmt.Println("Dir(p):", filepath.Dir(p))
  2. fmt.Println("Base(p):", filepath.Base(p))

::: {.en} We can check whether a path is absolute. :::

::: {.zh}

我们可以检查路径是否是绝对的。

:::

  1. fmt.Println(filepath.IsAbs("dir/file"))
  2. fmt.Println(filepath.IsAbs("/dir/file"))
  3. filename := "config.json"

::: {.en} Some file names have extensions following a dot. We can split the extension out of such names with Ext. :::

::: {.zh}

某些文件名在点后面有扩展名。我们可以使用Ext将扩展名从这些名称中分离出来。

:::

  1. ext := filepath.Ext(filename)
  2. fmt.Println(ext)

::: {.en} To find the file’s name with the extension removed, use strings.TrimSuffix. :::

::: {.zh}

要找到删除了扩展名的文件名,请使用strings.TrimSuffix

:::

  1. fmt.Println(strings.TrimSuffix(filename, ext))

::: {.en} Rel finds a relative path between a base and a target. It returns an error if the target cannot be made relative to base. :::

::: {.zh}

Rel找到 base *之间的相对路径。如果目标不能相对于base,则返回错误。

:::

  1. rel, err := filepath.Rel("a/b", "a/b/t/file")
  2. if err != nil {
  3. panic(err)
  4. }
  5. fmt.Println(rel)
  6. rel, err = filepath.Rel("a/b", "a/c/t/file")
  7. if err != nil {
  8. panic(err)
  9. }
  10. fmt.Println(rel)
  11. }
  1. $ go run file-paths.go
  2. p: dir1/dir2/filename
  3. dir1/filename
  4. dir1/filename
  5. Dir(p): dir1/dir2
  6. Base(p): filename
  7. false
  8. true
  9. .json
  10. config
  11. t/file
  12. ../c/t/file