7

[Golang] Write Lines to File

 2 years ago
source link: http://siongui.github.io/2018/04/09/go-writelines-to-file/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Golang] Write Lines to File

April 09, 2018

Write a list of strings (lines) to file in Go. First use strings.Join to convert lines to a single string. Then use ioutil.WriteFile to write the single string to file.

import (
      "io/ioutil"
      "strings"
)

func WriteLinesToFile(lines []string, filename string) (err error) {
      return ioutil.WriteFile(filename, []byte(strings.Join(lines, "\n")+"\n"), 0644)
}

If you want to know how to read lines from file, see [1].


Tested on: Ubuntu Linux 17.10, Go 1.10.1.


References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK