Go File Handling Explained with Examples

Updated 4 min read
Go File Handling featured image: cards showing WriteFile, ReadFile and bufio.Scanner

Go file handling lets your program save data to disk and read it back, from simple notes to large log files. In this post, you will write, read and append to files, read line by line and work with folders. Each idea comes with a short example that you can run yourself.

Every file function here returns an error, so a quick look at error handling in Go for beginners will help. We will also use defer to close files, which you met in writing and calling functions in Go.

What Is Go File Handling?

To begin with, file handling means creating, reading, changing and removing files from your code. Go keeps the main tools in the os package, with helpers in bufio and path/filepath.

For example, think of a notebook on your desk. You open it, write or read a page, and close it when you finish. Go file handling follows exactly the same steps.

Writing a File with os.WriteFile

err := os.WriteFile("notes.txt", []byte("Learn Go\nWrite tests\n"), 0644)
if err != nil {
	fmt.Println(err)
	return
}

In short, this one call creates the file, writes the bytes and closes it. However, if the file already exists, it replaces the old content. The number 0644 sets the file permissions, which we explain below.

Reading a File with os.ReadFile

data, err := os.ReadFile("notes.txt")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Print(string(data))
// Learn Go
// Write tests

In fact, ReadFile loads the whole file into memory at once. So it is perfect for small files like configs, but not for huge logs.

Go File Handling Step by Step: Open, Use, Close

Next, for more control, you open a file, work with it and then close it. The diagram below shows this flow, which every bigger file task follows.

Go File Handling diagram showing the open, check error, defer Close, read or write flow

Open the file, check the error, defer Close, then read or write until you are done.

Appending with os.OpenFile

f, err := os.OpenFile("notes.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
	fmt.Println(err)
	return
}
defer f.Close()

f.WriteString("Ship it\n")

First, the flags tell Go how to open the file. Here O_APPEND adds to the end, while O_WRONLY opens it for writing only. Also, defer f.Close() makes sure the file closes when the function ends.

Reading Line by Line with bufio.Scanner

file, err := os.Open("notes.txt")
if err != nil {
	fmt.Println(err)
	return
}
defer file.Close()

scanner := bufio.NewScanner(file)
line := 1
for scanner.Scan() {
	fmt.Println(line, scanner.Text())
	line++
}
if err := scanner.Err(); err != nil {
	fmt.Println(err)
}
// 1 Learn Go
// 2 Write tests
// 3 Ship it

For Go file handling at scale, a Scanner reads one line at a time, so memory stays low even for giant files. Remember to check scanner.Err() after the loop, because Scan simply stops on errors.

Go File Handling: Checking if a File Exists

_, err = os.ReadFile("missing.txt")
fmt.Println(err)                            // open missing.txt: no such file or directory
fmt.Println(errors.Is(err, fs.ErrNotExist)) // true

info, _ := os.Stat("notes.txt")
fmt.Println(info.Name(), info.Size()) // notes.txt 29

Use errors.Is with fs.ErrNotExist to check for a missing file. Meanwhile, os.Stat gives details such as the name and size in bytes.

Folders and Paths in Go File Handling

os.MkdirAll(filepath.Join("data", "logs"), 0755)
fmt.Println(filepath.Join("data", "logs", "app.log")) // data/logs/app.log

os.Remove("notes.txt")
os.RemoveAll("data")

MkdirAll creates a folder and any missing parents. Also, filepath.Join builds paths with the right slash for each system, so your code works on Windows, macOS and Linux.

File Permissions Explained

ValueOwnerGroup and othersTypical use
0644read and writeread onlyNormal files
0600read and writeno accessSecret files
0755full accessread and openFolders

In addition, the leading 0 means the number is octal. On Windows these values matter less, but always pass a sensible one.

Common Mistakes in Go File Handling

Problem you seeWhy it happensHow to fix it
open missing.txt: no such file or directoryThe path is wrong or relative to another folder.Check the path and your working folder.
“too many open files”The code never closed files in a loop.Close each file, ideally with defer.
Old content disappearsWriteFile replaced the file.Use OpenFile with O_APPEND.

Also, relative paths start from where you run the program, not where the code lives. File questions also appear in my Go interview questions and answers, so practise them there.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go file handling lives mainly in the os package.
  • WriteFile and ReadFile handle small files in one call.
  • For more control, open the file, defer Close, then read or write.
  • bufio.Scanner reads big files line by line.
  • Use filepath.Join for paths and errors.Is to spot missing files.

What’s Next?

You can now store data on disk. Next, we will share data over the network by building your first web server.

Coming soon: Go HTTP Server: Build Your First Web Server