直接贴代码:
package main import ( "fmt" "log" "os" "path/filepath" "strings" ) func substr(s string, pos, length int) string { runes := []rune(s) l := pos + length if l > len(runes) { l = len(runes) } return string(runes[pos:l]) } func getParentDirectory(dirctory string) string { return substr(dirctory, 0, strings.LastIndex(dirctory, "/")) } func getCurrentDirectory() string { dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { log.Fatal(err) } return strings.Replace(dir, "\\", "/", -1) } func main() { var str1, str2 string str1 = getCurrentDirectory()//获取当前目录 str2 = getParentDirectory(str1)获取上一级目录 fmt.Println(str2) }
有疑问加站长微信联系(非本文作者)