Golang : Read a file into an array or slice example
Ok, got a junior developer that wants to know how to read a text file content line by line into an array or slice. He is dealing with a legacy software that doesn't send out data either in JSON or XML format. The legacy software output is in text format.
Solution :
Use strings.Split()
function with newline (\n
) as the separator and ioutil.ReadFile()
function.
Here you go!
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
if len(os.Args) <= 1 {
fmt.Printf("USAGE : %s <target_filename> \n", os.Args[0])
os.Exit(0)
}
fileName := os.Args[1]
fileBytes, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sliceData := strings.Split(string(fileBytes), "\n")
fmt.Println(sliceData)
}
Reference:
See also : Golang : Display a text file line by line with line number example
By Adam Ng(黃武俊)
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+22.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+8.6k Golang : Populate or initialize struct with values example
+16.1k Golang : Convert slice to array
+17.9k Golang : Get command line arguments
+14k Golang : Recombine chunked files example
+5.3k Golang : Detect words using using consecutive letters in a given string
+20.4k PHP : Convert(cast) int to double/float
+16.1k Golang : Get IP addresses of a domain name
+16.8k Golang : How to tell if a file is compressed either gzip or zip ?
+17.4k Golang : Qt image viewer example
+13k Golang : Date and Time formatting
+16.1k Golang : Check if a string contains multiple sub-strings in []string?