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
+17.9k Golang : How to make function callback or pass value from function as parameter?
+3.7k Linux/MacOSX : Search and delete files by extension
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+9k Golang : Compare files modify date example
+18.7k Golang : Set or Add HTTP Request Headers
+4.3k Javascript : Change page title to get viewer attention
+12.4k Golang : Verify token from Google Authenticator App
+29.4k Golang : Download file example
+22.5k Golang : Use regular expression to validate domain name
+5k Golang : Shuffle array of list
+9.1k Golang : Read file and convert content to string
+6.1k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream