Read and Write file

Reading and writing files are basic tasks needed for many Go programs. First we’ll look at some examples of reading and writing files.

Read file

Golang has a built in ioutil lib, it support us can read file from file path

In the same folder contain go program which you will by this code, creating a folder with name testdata and text file hello.txt.

So you have a file with path ./testdata/hello.txt. Using function ReadFile of ioutil, you can read data in file as []byte array

package main

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

func main() {
	content, err := ioutil.ReadFile("./testdata/hello.txt")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("File contents", string(content))

}

Write file

ioutil lib also supports WriteFile function

When you call WriteFile function, code will create a file hello_write and write content into file

package main

import (
	"io/ioutil"
	"log"
)

func main() {
	message := []byte("Hello, Gophers!")
	err := ioutil.WriteFile("testdata/hello_write", message, 0644)
	if err != nil {
		log.Fatal(err)
	}
}

View on github

PreNext