Write string slice line by line to a text file
The bufio package provides an efficient buffered
Writer
which queues up bytes until a threshold is reached and then finishes the write operation to a file with minimum resources. The following source code snippet shows writing a string slice to a plain text file line-by-line.
Example
package main
import (
"bufio"
"log"
"os"
)
func main() {
sampledata := []string{"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Nunc a mi dapibus, faucibus mauris eu, fermentum ligula.",
"Donec in mauris ut justo eleifend dapibus.",
"Donec eu erat sit amet velit auctor tempus id eget mauris.",
}
file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
datawriter := bufio.NewWriter(file)
for _, data := range sampledata {
_, _ = datawriter.WriteString(data + "\n")
}
datawriter.Flush()
file.Close()
}
Most Helpful This Week
How do you write multi-line strings in Go?
How to convert String to Boolean Data Type Conversion in Go?
Golang program for implementation of Huffman Coding Algorithm
Undefined <variable/function> error in Golang
How do you handle HTTP client server compression in Go?
Contains, ContainsAny, Count and EqualFold string functions in Go Language
How do you handle HTTP redirects in Go?
Sierpinski triangle in Go Programming Language
How to delete an element from a Slice in Golang?
How to initialize the slice with values using a slice literal?