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
+12.3k Golang : How to display image file or expose CSS, JS files from localhost?
+19.9k Golang : Measure http.Get() execution time
+5.9k Facebook : How to force facebook to scrape latest URL link data?
+7.5k Golang : Shuffle strings array
+18.4k Golang : How to get hour, minute, second from time?
+8.8k Golang : Random integer with rand.Seed() within a given range
+14.6k Golang : Overwrite previous output with count down timer
+51.2k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+6.3k Apt-get to install and uninstall Golang
+10.3k Golang : Wait and sync.WaitGroup example
+11.2k Golang : How to determine a prime number?
+41.3k Golang : How to count duplicate items in slice/array?