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
+8.2k Golang : Read file with ioutil
+13.8k Golang : How to check for empty array string or string?
+13.9k Golang : Find location by IP address and display with Google Map
+11.3k Golang : Remove or trim extra comma from CSV
+19.2k Golang : Pipe output from one os.Exec(shell command) to another command
+6.4k Javascript : Push notifications to browser with Push.js
+11.9k Golang : Handle or parse date string with Z suffix(RFC3339) example
+8.8k Golang : Detect number of faces or vehicles in a photo
+6.8k Golang : get the current working directory of a running program
+5.6k Golang : Skip or discard items of non-interest when iterating example
+23.5k Golang : convert rune to integer value
+4.1k Golang : Display packages names during compilation