How to read a text file in Go

#go

Last updated on Jun 25, 2021 by Suraj Sharma



This tutorial is about how you can read a text file in Go using the ReadFile function.

ioutil.ReadFile function reads the text file named by filename and returns the contents as an array of bytes([]byte). It returns an error if the filename is not found.


func ReadFile(filename string) ([]byte, error)

Example


package main

import (
    "fmt"
    "io/ioutil"
    
)

func main () {
    contents, err := ioutil.ReadFile("./examples/hello-world.txt")
    if err != nil {
        fmt.Print(err.Error())
        return
    }
    fmt.Print(string(contents)) // "Hello World!"
}


Note: If you're using Go 1.16 or above then you can use os.ReadFile instead of ioutil.ReadFile function



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.