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
+12k Golang : Perform sanity checks on filename example
+22.1k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+8.1k Golang : Get final or effective URL with Request.URL example
+6.7k Golang : Humanize and Titleize functions
+9.2k Golang : How to control fmt or log print format?
+21.7k Golang : How to reverse slice or array elements order
+18.5k Golang : Generate thumbnails from images
+7.3k Golang : How to convert strange string to JSON with json.MarshalIndent
+5.8k Golang : List all packages and search for certain package
+10.5k Golang : Create matrix with Gonum Matrix package example
+7.3k Golang : Scanf function weird error in Windows
+5.9k Golang : Compound interest over time example