go 从路径获取文件信息

  • 2022-07-09
  • 浏览 (1465)

golang 获取文件名称、后缀、纯文件名

package main

import (
	"fmt"
	"path"
	"strings"
	"testing"
)

func TestFileName(t *testing.T) {
	var filePath = "sx/test.txt"

	//获取文件名称带后缀
	fileNameWithSuffix := path.Base(filePath)

	//获取文件的后缀(文件类型)
	ext := path.Ext(fileNameWithSuffix)

	//获取文件名称(不带后缀)
	fileNameNoSuffix := strings.TrimSuffix(fileNameWithSuffix, ext)

	fmt.Printf("fileNameWithSuffix: %s\n", fileNameWithSuffix)
	fmt.Printf("ext:                %s\n", ext)
	fmt.Printf("fileNameNoSuffix:   %s\n", fileNameNoSuffix)
}

执行命令: go test -v file_test.go

运行结果:

fileNameWithSuffix: test.txt
ext:                .txt
fileNameNoSuffix:   test
0  赞