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
+3.5k JavaScript : Rounding number to decimal formats to display currency
+17k Golang : Populate dropdown with html/template example
+8k Golang : Get all countries currencies code in JSON format
+11.6k Golang : List objects in AWS S3 bucket
+12.5k Golang : syscall.Socket example
+22.1k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+9.3k Golang : Command line file upload program to server example
+3.5k Nginx and PageSpeed build from source CentOS example
+6.8k Golang : Check if integer is power of four example
+3.5k MariaDB/MySQL : How to get version information
+15.6k Golang : Parse date string and convert to dd-mm-yyyy format
+6.8k Prevent Write failed: Broken pipe problem during ssh session with screen command