File I/O with ioutil¶
The ioutil package in Go's standard library provides convenient functionality for handling file input and output (I/O) operations, abstracting away lower-level details^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md].
Importing the Package¶
Since ioutil is part of the Go standard library, it can be imported directly into your application^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md].
import (
"io/ioutil"
)
Reading Files¶
To read data from a file, the ReadFile function is used^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]. This function accepts a file path as an argument and returns the file's contents as a byte slice ([]byte), along with an error object^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md].
fileBytes, err := ioutil.ReadFile("./videos.json")
if err != nil {
panic(err)
}
fileContent := string(fileBytes)
fmt.Println(fileContent)
It is common practice to check the error immediately; if an error occurs, the code above uses panic to halt execution^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md].
Writing Files¶
To write data to a file, the WriteFile function is utilized^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]. This function requires three arguments:
1. The destination file path (e.g., "./videos-updated.json").
2. The data to be written, provided as a byte slice.
3. The file permission mode (e.g., 0644).
err = ioutil.WriteFile("./videos-updated.json", videoBytes, 0644)
if err != nil {
panic(err)
}
In this example, videoBytes typically represents data that has been serialized (converted) into a byte format, such as JSON^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md].
Related Concepts¶
- Go programming language
- [[Data serialization]]
Sources¶
^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]