bnarang
(Bhupinder Singh Narang)
March 17, 2018, 4:08am
1
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?
nstratos
(Stratos)
March 17, 2018, 7:31am
2
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
bins
(Sebastien Binet)
March 17, 2018, 8:17am
3
One should probably use ‘bufio.NewScanner’ to read the file line by line.
1 Like
NobbZ
(Norbert Melzer)
March 17, 2018, 8:24am
4
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
bnarang
(Bhupinder Singh Narang)
March 20, 2018, 2:06am
5
Thank you. I was able to fix the problem with bufio.NewScaner. Though, other suggestions have helped in increasing my understanding of the issue
system
(system)
Closed
June 18, 2018, 2:06am
6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.