Golang filepath

shengjuntu · · 1669 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

写一个小函数测试:
func DumpPath(path string) {
    m := make(map[string]string)

   
    base := filepath.Base(path)
    ext := filepath.Ext(path)
    dir,file := filepath.Split(path)

    m["path"] = path
    m["base"] = base
    m["ext"] = ext
    m["dir"] = dir
    m["file"] = file
    for k,v := range m {
        fmt.Println(k , ":", v)
    }
}

-------------------------------------------------------------------------------------

CASE 1:

path : ../data/test_1.txt
base : test_1.txt
ext : .txt
dir : ../data/
file : test_1.txt

容易以为base 和 file是一个意思。但是不是的。

-------------------------------------------------------------------------------------

CASE 2:

ext :
dir : d:
file :
path : d:
base : \

此为官方文档解释:

Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.

路径被分解,最后的一个就是Base.

Split splits path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.

公式:path = dir+file 好理解。

就是路径是由目录和文件名串起来的。

 

按照这个规则,Join就是逆过程。

fmt.Println(filepath.Join("c:/", "b","a", ".txt"))

c:\b\a\.txt

所以想得到c:\b\a.txt

要用 filepath.Join("c:/", "b","a.txt")

 

*****

Go细致的地方,后缀中是带有   .  号的。

常见的一个操作就是去掉文件的后缀。

strings.TrimSuffix(path, filepath.Ext(path))

这个符合一个规定就是:file = name + ext

那个“."号属于后缀。

 

 

 

 


有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:shengjuntu

查看原文:Golang filepath

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1669 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传