Working with ReadDir

I’ve the below code for reading .txt files and add them as constant in another .go file.

// file a.txt

// file b.txt

the code works perfectly for and generate the required output as:

package main 

const (
a = `Hello`
b = `Gopher`

The code is:

package main

import (

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)

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!

Check your error returns. (Hint: and compare what readdir returns with what the path to the file is from where your program is running.)

1 Like

The error happened to be at os.Open(f.Name()):

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

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

The error is:

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

goroutine 1 [running]:
	c:/GoApps/playground/script/includedText.go:28 +0x48e

which means by:

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

The system read the correct files names, but once it came to:

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

It was trying to read the files from the root directory, not from the /texts this had been fixed by:

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.