I’ve the below code for reading .txt
files and add them as constant in another .go
file.
// file a.txt
Hello
// file b.txt
Gopher!
the code works perfectly for and generate the required output as:
package main
const (
a = `Hello`
b = `Gopher`
)
The code is:
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"))
}
The above works perfectly if the .txt
files are in the root directory ioutil.ReadDir(".")
But if I put the .txt
files in sub folder in the root, and named it text
, and changed the code to be:
fs, _ := ioutil.ReadDir("./texts")
Then the output I get is:
package main
const (
a = ``
b = ``
)
Which means the code saw the files, and read their names, but for some reason not reading their contents!