Golang: Write to File

By Xah Lee. Date: . Last updated: .

Write to a file using os.WriteFile

err := os.WriteFile(filepath, byte_slice, file_perm_octal)

package main

import "os"

func main() {

	outpath := "xx69447.txt"

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

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

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

Write to a file using WriteString

var fileObject, err = os.Create(filepath) 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)

}

Golang

Compile and Run

String

Types and Values

Branching and Loop

Data Structure

Function

Misc

Examples

Reference