Golang filepath

写一个小函数测试:
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

那个“."号属于后缀。

 

 

 

 

转载于:https://my.oschina.net/u/612750/blog/759026

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值