go文件夹遍历
path/filepath 包涉及到路径操作时,路径分隔符使用 os.PathSeparator. Go是一个跨平台的语言,不同系统,路径表示方式有所不同,比如 Unix 和 Windows 差别很大.本包能够处理所有的文件路径,不管是什么系统.
Go标准库中还有path, path 和 path/filepath 函数有点重复,大部分情况下建议使用 path/filepath.
1.示例代码:package path
package main;
import (
"fmt"
"path"
)
//go语言path包的学习
func main() {
//返回路径的最后一个元素
fmt.Println(path.Base("./github.com/mojocn/c"));
//如果路径为空字符串,返回.
fmt.Println(path.Base(""));
//如果路径只有斜线,返回/
fmt.Println(path.Base("///"));
//返回等价的最短路径
//1.用一个斜线替换多个斜线
//2.清除当前路径.
//3.清除内部的..和他前面的元素
//4.以/..开头的,变成/
fmt.Println(path.Clean("./github.com/mojocn/../"));
//返回路径最后一个元素的目录
//路径为空则返回.
fmt.Println(path.Dir("./github.com/mojocn/c"));
//返回路径中的扩展名
//如果没有点,返回空
fmt.Println(path.Ext("./github.com/mojocn/c/d.jpg"));
//判断路径是不是绝对路径
fmt.Println(path.IsAbs("./github.com/mojocn/c"));
fmt.Println(path.IsAbs("/github.com/mojocn/c"));
//连接路径,返回已经clean过的路径
fmt.Println(path.Join("./a", "b/c", "../d/"));
//匹配文件名,完全匹配则返回true
fmt.Println(path.Match("*", "a"));
fmt.Println(path.Match("*", "a/b/c"));
fmt.Println(path.Match("\\b", "b"));
//分割路径中的目录与文件
fmt.Println(path.Split("./github.com/mojocn/c/d.jpg"));
}
2.示例代码:package path/filepath
filepath.Join("C:/a", "/b", "/c") 拼接目录
package main;
import (
"path/filepath"
"fmt"
"os"
)
//学习filepath包,兼容各操作系统的文件路径
func main() {
//返回所给路径的绝对路径
path, _ := filepath.Abs("./1.txt");
fmt.Println(path);
//返回路径最后一个元素
fmt.Println(filepath.Base("./1.txt"));
//如果路径为空字符串,返回.
fmt.Println(filepath.Base(""));
//如果路径只有斜线,返回/
fmt.Println(filepath.Base("///"));
//返回等价的最短路径
//1.用一个斜线替换多个斜线
//2.清除当前路径.
//3.清除内部的..和他前面的元素
//4.以/..开头的,变成/
fmt.Println(filepath.Clean("C:/github.com/mojocn/../c"));
fmt.Println(filepath.Clean("./1.txt"));
//返回路径最后一个元素的目录
//路径为空则返回.
fmt.Println(filepath.Dir("./github.com/mojocn/c"));
fmt.Println(filepath.Dir("C:/github.com/mojocn/c"));
//返回链接文件的实际路径
path2, _ := filepath.EvalSymlinks("1.lnk");
fmt.Println(path2);
//返回路径中的扩展名
//如果没有点,返回空
fmt.Println(filepath.Ext("./github.com/mojocn/c/d.jpg"));
//将路径中的/替换为路径分隔符
fmt.Println(filepath.FromSlash("./github.com/mojocn/c"));
//返回所有匹配的文件
match, _ := filepath.Glob("./*.go");
fmt.Println(match);
//判断路径是不是绝对路径
fmt.Println(filepath.IsAbs("./github.com/mojocn/c"));
fmt.Println(filepath.IsAbs("C:/github.com/mojocn/c"));
//连接路径,返回已经clean过的路径
fmt.Println(filepath.Join("C:/a", "/b", "/c"));
//匹配文件名,完全匹配则返回true
fmt.Println(filepath.Match("*", "a"));
fmt.Println(filepath.Match("*", "C:/github.com/mojocn/c"));
fmt.Println(filepath.Match("\\b", "b"
