Unable to read text file properly

Hi,

My text file looks like this :

email:"abc@gmail.com"
password:“xyz”

I have written code to read text file, but I am unable to split them properly into list

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"reflect"
	"strings"
)

func main() {

	file, err := ioutil.ReadFile("credentials.txt")
	if err != nil {
		log.Fatal(err)
	}

	x := string(file)
	fmt.Println(x)
	y := strings.Replace(x, `\n`, "\n", -1)
	z := strings.Split(y, "\n")
	fmt.Println(z)
}

Output is:

[]string
]password:xyz"il.com"`

Can you please help me what’s wrong with code?

I suggest printing the file using fmt.Printf("%q\n", file) to see all the special characters escaped. The replace shouldn’t be needed. Assuming the file contains email\npassword:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"
)

const input = `email:"abc@gmail.com"
password:"xyz"`

func main() {
	file, err := ioutil.ReadAll(strings.NewReader(input))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%q\n", file)

	s := strings.Split(string(file), "\n")
	fmt.Printf("%#v\n", s)
}

(Playground link)

1 Like

One should probably use ‘bufio.NewScanner’ to read the file line by line.

1 Like

Your input file seems to have windows line endings. Save it again with Linux endings or handle windows line endings in your code.

2 Likes

Thank you. I was able to fix the problem with bufio.NewScaner. Though, other suggestions have helped in increasing my understanding of the issue

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