How to read a text file in Golang

Last updated on Jun 25, 2021 by Suraj Sharma

This tutorial is about how you can read a text file in Golang 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)


package main

import (

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

Note: If you're using Golang 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.