How to read file in Go

Here is the basic way to read a file in go using the ioutil go module. The ReadFile function requires only the file name. Then as output will give the content as a []byte and the error that will be nil if the file has successfully been read.

Code

content, err := os.ReadFile(FILE NAME)

Example: read a file with ioutil

read_file.go
package main

import (
	"fmt"
	"os"
	"log"
)

func main() {
	if content, err := os.ReadFile("text_file.txt"); err == nil{
		fmt.Println(string(content))
	}else{
		log.Fatal(err)
	}
}

Other articles