{"title":"Golang读取运行目录下文件夹所有txt文件路径 - 代码示例","description":"本文介绍了如何使用Golang读取运行目录下指定文件夹中的所有txt文件路径,提供了详细的代码示例和解释。","keywords":"golang, 文件夹遍历, txt文件, 读取文件路径, filepath.Walk, os.Getwd, filepath.Join, strings.HasSuffix","content":"\u003cp\u003e您可以使用filepath.Walk函数来遍历目录下的所有文件,然后使用.txt后缀来过滤出所有的txt文件。\u003c/p\u003e\n\n\u003cp\u003e以下是一个示例代码:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e\u003cspan style="color: #999; font-weight: bold;">package\u003c/span\u003e main\n\n\u003cspan style="color: #999; font-weight: bold;">import\u003c/span\u003e (\n\t\u003cspan style="color: #999; font-weight: bold;">"fmt"\u003c/span\u003e\n\t\u003cspan style="color: #999; font-weight: bold;">"os"\u003c/span\u003e\n\t\u003cspan style="color: #999; font-weight: bold;">"path/filepath"\u003c/span\u003e\n\t\u003cspan style="color: #999; font-weight: bold;">"strings"\u003c/span\u003e\n)\n\n\u003cspan style="color: #999; font-weight: bold;">func\u003c/span\u003e main() {\n\t// 获取当前运行目录\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t fmt.Println(\u003cspan style="color: #999; font-weight: bold;">"获取当前目录失败:\u003c/span\u003e", err)\n\t return\n\t}\n\n\t// 拼接目标文件夹路径\n\ttargetDir := filepath.Join(dir, \u003cspan style="color: #999; font-weight: bold;">"a"\u003c/span\u003e)\n\n\t// 遍历目标文件夹下的所有文件\n\terr := filepath.Walk(targetDir, func(path string, info os.FileInfo, err error) error {\n\t if err != nil {\n\t fmt.Printf(\u003cspan style="color: #999; font-weight: bold;">"访问文件时发生错误: %v\n"\u003c/span\u003e, err)\n\t return err\n\t }\n\n\t // 判断是否为txt文件\n\t if !info.IsDir() && strings.HasSuffix(info.Name(), \u003cspan style="color: #999; font-weight: bold;">"\u002etxt"\u003c/span\u003e) {\n\t fmt.Println(path)\n\t }\n\n\t return nil\n\t})\n\n\tif err != nil {\n\t fmt.Printf(\u003cspan style="color: #999; font-weight: bold;">"遍历文件夹时发生错误: %v\n"\u003c/span\u003e, err)\n\t return\n\t}\n}\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e在上面的示例中,我们首先使用os.Getwd函数获取当前运行目录,然后使用filepath.Join函数拼接目标文件夹的路径。接下来,我们使用filepath.Walk函数遍历目标文件夹下的所有文件,通过判断文件是否为txt文件来输出文件路径。\u003c/p\u003e

Golang读取运行目录下文件夹所有txt文件路径 - 代码示例

原文地址: http://www.cveoy.top/t/topic/pCXq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录