Go - write to file with ioutil.WriteFile

In this example, we will show you how to write to file in Go with an example.

The outil.WriteFile writes data to the specified file. This is a higher-level convenience function. The opening and closing of the file is handled for us.

Go - write to file with ioutil.WriteFile

The example writes a string to a file with ioutil.WriteFile.

Let's first create an empty 'sample.txt' file that we want to write upon.

Let's create a file named go_example.go and add the following content to it:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
)

func main() {

    val := "My first fav programming languge is Go Lang \nMy second fav programming languge is Java \nMy third fav programming languge is Python\n"
    data := []byte(val)

    err := ioutil.WriteFile("data.txt", data, 0)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("done")
}

Output:

G:\GoLang\examples>go run go_example.go
done

After executing above program, open the 'sample.txt' file and you should able to see the content of the file as below:

My first fav programming languge is Go Lang 
My second fav programming languge is Java 
My third fav programming languge is Python

Comments