Table of contents
1.
Introduction
2.
Reading and Writing Files
3.
Methods of Reading & Writing Files
4.
Reading and Writing Files
5.
Example
6.
Reading a file line by line
6.1.
Example
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Go Reading & Writing Files

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will be learning how to read and write files effectively in golang within your filesystem. Meanwhile, moving to the main topic, we shall learn about some previous concepts like what a file is. A file is an essential entity that is used to store information.

Reading and Writing Files

Golang offers a vast inbuilt library that performs read and write operations on files. The io/ioutil module runs the files on the local system. This module is also used to write content to the file. The fmt module is used to format the I/O with functions to read the input from the stdin and print output to the stdout. 

Methods of Reading & Writing Files

Reading and Writing Files

To read the files from the local filesystem, we need to use the 'io/ioutil' module. We need to pull some contents of a file into memory.

Example

Content of test.txt

Welcome to Coding Ninjas. This code demonstrates reading and writing operations to a file in Go lang.
package main
 
import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
)
 
func CreateFile() {
 
   
    fmt.Printf("Writing to a file in Go lang\n")
   
   
    file, err := os.Create("test.txt")
   
    if err != nil {
        log.Fatalf("failed creating file: %s", err)
    }
   
    defer file.Close()
   
    len, err := file.WriteString("Welcome to Coding Ninjas." +
            "This code demonstrates reading and writing" +
                        "operations to a file in Go lang.")
 
    if err != nil {
        log.Fatalf("failed writing to file: %s", err)
    }
 
    fmt.Printf("\nFile Name: %s", file.Name())
    fmt.Printf("\nLength: %d bytes", len)
}
 
func ReadFile() {
 
    fmt.Printf("\n\nReading the file in Go lang.\n")
    fileName := "test.txt"
   
    data, err := ioutil.ReadFile("test.txt")
    if err != nil {
        log.Panicf("failed to read data from file: %s", err)
    }
    fmt.Printf("\nFile Name: %s", fileName)
    fmt.Printf("\nSize: %d bytes", len(data))
    fmt.Printf("\nData: %s", data)
 
}
 
func main() {
 
    CreateFile()
    ReadFile()
}

Output

Writing to a file in Go lang
 
File Name: test.txt
Length: 101 bytes
 
Reading a file in Go lang.
 
File Name: test.txt
Size: 101 bytes
Data: Welcome to Coding Ninjas. This code demonstrates reading and writing operations to a file in Go lang.

In this example, we have created a file; we input the data into that file. After inputting the data, we used several inbuilt functions to print the file name and size. We also print the data of the file.

Reading a file line by line

A file can also be read line by line—the function bufio.ReadString() is used to read the input line by line.

Example

package main
 
import (
    "bufio"
    "flag"
    "fmt"
    "io"
    "os"
)
 
func lineByLine(file string) error {
    var err error
    fd, err := os.Open(file)
    if err != nil {
        return err
    }
    defer fd.Close()
 
    reader := bufio.NewReader(fd)
    for {
        line, err := reader.ReadString('\n')
        if err == io.EOF {
            break
        } else if err != nil {
            fmt.Printf("error reading file %s", err)
            break
        }
        fmt.Print(line)
    }
    return nil
}
 
func main() {
    flag.Parse()
    if len(flag.Args()) == 0 {
        fmt.Printf("usage: lByL <file1> [<file2> ...]\n")
        return
    }
 
    for _, file := range flag.Args() {
        err := lineByLine(file)
        if err != nil {
            fmt.Println(err)
        }
    }
}

 Output

usage: lByL <file1> [<file2> ...]

In this example, we have read the file's content one by one. We checked certain conditions, and we showed a certain output.

FAQs

  1. How do you read a file in go?
    To read the files in Go, we use several packages: os, ioutil, io, and bufio.
     
  2. What types of files can I read in Go?
    In Go, we can read several types of files: CSV, PNG, or some proprietary data format.
     
  3.  How do I write content to a file in Go?
    To write the content in the file, we need to use the io/util module. 

Key Takeaways

In this article, we have extensively discussed the topic of Reading and Writing Files and their implementation in Golang.

We also explained a bit about Reading and Writing Files. We also discussed some of the inbuilt methods in the library. We took specific examples of reading and writing in files and their explanation. 

We hope that this blog has helped you enhance your knowledge regarding Reading and Writing Files in GoLang and if you would like to learn more, check out our articles on Custom Errors in GoGo Command Arguments

Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass