Golang中如何使用ReadDir读取目录内容
Golang中如何使用ReadDir读取目录内容
以下代码用于读取 .txt 文件,并将它们作为常量添加到另一个 .go 文件中。
// file a.txt
Hello
// file b.txt
Gopher!
代码运行正常,并生成了所需的输出:
package main
const (
a = `Hello`
b = `Gopher`
)
代码如下:
package main
import (
"io"
"io/ioutil"
"os"
"strings"
)
func main() {
fs, _ := ioutil.ReadDir(".")
out, _ := os.Create("textfiles.go")
out.Write([]byte("package main \n\nconst (\n"))
for _, f := range fs {
if strings.HasSuffix(f.Name(), ".txt") {
out.Write([]byte(strings.TrimSuffix(f.Name(), ".txt") + " = `"))
f, _ := os.Open(f.Name())
io.Copy(out, f)
out.Write([]byte("`\n"))
}
}
out.Write([]byte(")\n"))
}
如果 .txt 文件位于根目录 ioutil.ReadDir(".") 下,上述代码可以完美运行。
但是,如果我将 .txt 文件放在根目录的子文件夹中,并将其命名为 text,并将代码改为:
fs, _ := ioutil.ReadDir("./texts")
那么我得到的输出是:
package main
const (
a = ``
b = ``
)
这意味着代码看到了文件,并读取了它们的名称,但由于某种原因没有读取它们的内容!
更多关于Golang中如何使用ReadDir读取目录内容的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
检查你的错误返回。(提示:并比较 readdir 返回的内容与程序运行时文件的路径。)
func main() {
fmt.Println("hello world")
}
更多关于Golang中如何使用ReadDir读取目录内容的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
问题在于使用 ioutil.ReadDir("./texts") 时,代码仍然在当前目录下打开文件。需要根据子目录路径来打开文件。
修改后的代码:
package main
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func main() {
dir := "./texts"
fs, _ := ioutil.ReadDir(dir)
out, _ := os.Create("textfiles.go")
out.Write([]byte("package main \n\nconst (\n"))
for _, f := range fs {
if strings.HasSuffix(f.Name(), ".txt") {
out.Write([]byte(strings.TrimSuffix(f.Name(), ".txt") + " = `"))
// 使用完整路径打开文件
filePath := filepath.Join(dir, f.Name())
f, _ := os.Open(filePath)
io.Copy(out, f)
f.Close()
out.Write([]byte("`\n"))
}
}
out.Write([]byte(")\n"))
out.Close()
}
关键修改:
- 使用
filepath.Join(dir, f.Name())构建完整的文件路径 - 添加了文件关闭操作
f.Close() - 添加了输出文件关闭操作
out.Close()
如果 texts 目录结构如下:
texts/
├── a.txt
└── b.txt
代码将正确生成:
package main
const (
a = `Hello`
b = `Gopher!`
)


