๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Go File IO

File IO is reading and writing files from a program. A file holds data after the program ends.

Write a file and read it back

WriteFile writes the text to note.txt in one call. The number 0644 sets who may read or write the new file. ReadFile then reads the file back.

package main

import (
	"fmt"
	"os"
)

func main() {
	err := os.WriteFile("note.txt", []byte("Saved by Go"), 0644)
	if err != nil {
		fmt.Println("Could not write the file")
		return
	}
	data, err := os.ReadFile("note.txt")
	if err != nil {
		fmt.Println("Could not read the file")
		return
	}
	fmt.Println(string(data))
}

Create a file and write two lines

Create makes an empty file named lines.txt. WriteString writes text into the open file.

package main

import (
	"fmt"
	"os"
)

func main() {
	file, err := os.Create("lines.txt")
	if err != nil {
		fmt.Println("Could not create the file")
		return
	}
	file.WriteString("First line\n")
	file.WriteString("Second line\n")
	file.Close()
	data, err := os.ReadFile("lines.txt")
	if err != nil {
		fmt.Println("Could not read the file")
		return
	}
	fmt.Print(string(data))
}

A missing file gives an error

No file named missing.txt exists in the folder. ReadFile returns an error, and the program prints its own line.

package main

import (
	"fmt"
	"os"
)

func main() {
	data, err := os.ReadFile("missing.txt")
	if err != nil {
		fmt.Println("Could not read the file")
		return
	}
	fmt.Println(string(data))
}

Count the lines in a file

WriteFile writes three lines of text. Count counts the newline marks in the text that ReadFile returns.

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	err := os.WriteFile("list.txt", []byte("apple\nbanana\ncherry\n"), 0644)
	if err != nil {
		fmt.Println("Could not write the file")
		return
	}
	data, err := os.ReadFile("list.txt")
	if err != nil {
		fmt.Println("Could not read the file")
		return
	}
	text := string(data)
	fmt.Println("Lines:", strings.Count(text, "\n"))
}

Example

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	err := os.WriteFile("notes.txt", []byte("Wake up early\nRead a book\nWrite some code\n"), 0644)
	if err != nil {
		fmt.Println("Could not write the file")
		return
	}
	data, err := os.ReadFile("notes.txt")
	if err != nil {
		fmt.Println("Could not read the file")
		return
	}
	lines := strings.Split(strings.TrimSpace(string(data)), "\n")
	for i, line := range lines {
		fmt.Printf("%d. %s\n", i+1, line)
	}
}

Key points

  • File IO means reading and writing files from a program.
  • Use os.WriteFile to write a whole text to a file in one call.
  • Use os.ReadFile to read a whole file back in one call.
  • ReadFile returns bytes, and string(data) turns those bytes into text.
  • Use os.Create to make a new file that a program fills step by step.
  • WriteString writes text into a file made with os.Create.
  • A file call reports a problem through an error value.

In this example, WriteFile writes three lines to notes.txt. ReadFile reads the file back as bytes. TrimSpace removes the last newline mark, and Split cuts the text into one string per line. The loop prints each line with its number, starting at 1.

Note

Each file in this lesson sits in the folder where the program runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

A program calls os.ReadFile on a file that does not exist. What does ReadFile return beside the data?