Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. os.ReadFile() / WriteFile()

os.ReadFile() / WriteFile()

Convenience functions for reading and writing file contents all at once. Since Go 1.16, os.ReadFile() and os.WriteFile() are available in the standard library.

Syntax

// Read an entire file (returns []byte)
data, err := os.ReadFile("file path")

// Write []byte to a file (creates the file if it does not exist)
err := os.WriteFile("file path", data, 0644)

Function List

FunctionDescription
os.ReadFile(name)Reads the entire contents of a file and returns them as a byte slice. Available since Go 1.16.
os.WriteFile(name, data, perm)Writes a byte slice to a file. If the file does not exist, it is created with the specified permissions.
string(data)Converts a byte slice to a string. Use this when you want to treat the read contents as text.

Sample Code

package main

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

func main() {
	// Write text to a file
	content := "Go language study notes\nFile operations are easy\n"
	err := os.WriteFile("memo.txt", []byte(content), 0644)
	if err != nil {
		fmt.Println("Write error:", err)
		return
	}
	fmt.Println("Wrote memo.txt")

	// Read the entire file
	data, err := os.ReadFile("memo.txt")
	if err != nil {
		fmt.Println("Read error:", err)
		return
	}

	// Convert the byte slice to a string and print it
	text := string(data)
	fmt.Println("--- File contents ---")
	fmt.Print(text)

	// Process the read contents and overwrite the file
	upper := strings.ToUpper(text)
	os.WriteFile("memo.txt", []byte(upper), 0644)
	fmt.Println("Converted contents to uppercase and overwrote the file")

	// Clean up
	os.Remove("memo.txt")
}

Notes

os.ReadFile() and os.WriteFile() handle opening and closing the file internally, so your code stays very concise. They are the simplest option when working with configuration files or text files.

When working with large files, be aware of memory usage, as the entire contents are loaded into memory at once. For files of several hundred MB or more, it is more appropriate to use bufio for stream processing. The permission 0644 means "owner can read and write; others can only read."

If you find any errors or copyright issues, please .