filepath.Join 删除点

filepath.Join removes dot

我在为 rsync 创建路径时遇到问题。

x := filepath.Join("home", "my_name", "need_folder", ".")
fmt.Println(x)

我得到 "home/my_name/need_folder",但需要 "home/my_name/need_folder/.",没有 concat 如何修复?在 linux 名为“.”的文件夹中并非不可能。

谢谢!

您不能使用 filepath.Join() 执行此操作,如其文档所述:

Join calls Clean on the result...

并且由于 . 表示“当前”目录,它将被 filepath.Clean() 删除:

It applies the following rules iteratively until no further processing can be done:

  1. [...]

  2. Eliminate each . path name element (the current directory).

事实上你根本不能用path/filepath包做你想做的事,不支持这个操作。

您需要手动使用字符串连接。使用filepath.Separator,这样就安全了:

x := filepath.Join("home", "my_name", "need_folder") +
    string(filepath.Separator) + "."
fmt.Println(x)

输出(在 Go Playground 上尝试):

home/my_name/need_folder/.

当你调用 filepath.Join 它实际上有两个步骤

  1. 将路径与分隔符连接起来,通过这一步实际上你会得到"home/my_name/need_folder/."
  2. clean the path,会对path做词法处理,return最短路径名等于第1步得到的path

在第 2 步中,如果您阅读源代码,您会发现它调用了一个 Clean 函数,该函数将

Eliminate each . path name element (the current directory).

你可以试试:

x := filepath.Join("home", "my_name", "need_folder", ".", "." , ".") fmt.Println(x)

你仍然会得到相同的结果。

如果建议您在这种情况下使用 concat :)