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


错误发生在 os.Open(f.Name()) 处:

func check(e error) {
	if e != nil {
		_ = reflect.TypeOf(e)
		panic(e)
	}
}

f, err := os.Open(f.Name())
check(err)

错误信息是:

panic: open a.txt: The system cannot find the file specified.

goroutine 1 [running]:
main.check(...)
	c:/GoApps/playground/script/includedText.go:14
main.main()
	c:/GoApps/playground/script/includedText.go:28 +0x48e

这意味着通过:

fs, _ := ioutil.ReadDir("./texts")

系统读取到了正确的文件名,但是当执行到:

f, err := os.Open(f.Name())

时,它试图从 root 根目录读取文件,而不是从 /texts 目录。这个问题通过以下方式得以修复:

f, err := os.Open("./texts/" + f.Name())

问题在于使用 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()
}

关键修改:

  1. 使用 filepath.Join(dir, f.Name()) 构建完整的文件路径
  2. 添加了文件关闭操作 f.Close()
  3. 添加了输出文件关闭操作 out.Close()

如果 texts 目录结构如下:

texts/
├── a.txt
└── b.txt

代码将正确生成:

package main 

const (
a = `Hello`
b = `Gopher!`
)
回到顶部