Skip to content

File I/O with Go's ioutil package

The io/ioutil package in Go provides standard library utilities for handling input/output (I/O) operations, specifically for reading from and writing to files^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]. It allows data to be managed externally from the application logic, separating the codebase from the data it processes^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md].

Importing the Package

As part of the Go standard library, ioutil can be imported directly into a Go file^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md].

import (
    "io/ioutil"
)

Reading Files

To read the entire contents of a file into memory, the ioutil.ReadFile function is used^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]. This function takes a file path as an argument and returns the file's content as a byte slice ([]byte), along with an error object^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md].

fileBytes, err := ioutil.ReadFile("./videos.json")

if err != nil {
    panic(err)
}

fileContent := string(fileBytes)
fmt.Println(fileContent)

The byte slice returned by ReadFile can be converted to a string or unmarshaled into a struct, for example, when handling JSON data^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md].

Writing Files

To write data to a file, ioutil.WriteFile is used^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]. This function creates a file if it does not exist, or truncates it if it does. It accepts three arguments: the filename, the data byte slice, and the file permissions^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md].

err = ioutil.WriteFile("./videos-updated.json", videoBytes, 0644)
if err != nil {
    panic(err)
}

In the example above, 0644 represents the standard Unix file permission bits (read/write for owner, read-only for group and others)^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md].

  • [[JSON in Go]]
  • [[Error handling]]
  • [[File permissions]]

Sources

  • 400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md