Golang: Write to File

By Xah Lee. Date: . Last updated: .

Here's one way of writing to a file.

err := ioutil.WriteFile(file_path, byte_slice, file_perm_octal)

package main

import "io/ioutil"

func main() {

	mytext := []byte(`mountain and river`)

	outpath := "xx69447.txt"

	err := ioutil.WriteFile(outpath, mytext, 0644)

	if err != nil {
		panic(err)
	}
}

Here's another way to write to file.

var fileObject, err = os.Create(file_path) var bytesWritten, errW = fileObject.WriteString(content_str)

package main

import "fmt"
import "os"

var path = "xxtest.txt"

var contentX = "something"

func main() {

	var fll, err = os.Create(path)
	if err != nil {
		panic(err)
	}
	defer fll.Close()

	var bytesWritten, errW = fll.WriteString(contentX)
	if errW != nil {
		panic(errW)
	}

	fmt.Printf("bytes written: %v\n", bytesWritten)

}

If you have a question, put $5 at patreon and message me.

Golang

Examples

Reference