ProgramGuru

Reading and Writing Files

Start with Reading and Writing Files

Go can read and write file contents through the os package, allowing programs to persist information between runs.

What you’ll learn

  • Explain the main purpose of reading and writing files.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

os.WriteFile(path, data, perm) writes all provided bytes, and os.ReadFile reads a file into a byte slice. For portable examples, create a temporary directory rather than assuming access to a fixed user-specific path.

Always check errors. Writing with os.WriteFile replaces the target file’s content; for append, streaming or large files use a more appropriate file handle and mode. Be careful about file permissions and untrusted paths.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for filesCheck every filesystem operation and clean up temporary resources.Create temp directoryStep 1WriteFileStep 2ReadFileStep 3CleanupStep 4Check every filesystem operation and clean up temporary resources.
Check every filesystem operation and clean up temporary resources.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	folder, err := os.MkdirTemp("", "course-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(folder)
	path := filepath.Join(folder, "note.txt")
	if err := os.WriteFile(path, []byte("Learning files"), 0600); err != nil {
		panic(err)
	}
	data, err := os.ReadFile(path)
	if err != nil {
		panic(err)
	}
	fmt.Println("Contents:", string(data))
}

Output

Contents: Learning files

Trace what the program does

MkdirTemp creates a private unique directory. WriteFile stores a short text file there, ReadFile retrieves the bytes, and the deferred cleanup deletes the temporary directory.

Avoid common mistakes

  • Use ReadFile for appropriately sized files; enormous files may need streaming.
  • os.WriteFile overwrites an existing file with the same name.

Try it yourself

Change the saved text and write a second file in the same temporary directory.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Why use MkdirTemp in this example?
Choose one answer. You can try again.

Answer and explanation

To avoid fixed machine-dependent paths and name collisions

Correct. MkdirTemp creates a private unique directory.

What you should remember

You have practiced Reading and Writing Files in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: The bufio Package →