Files and IO

Contents
os.ReadFile
os.WriteFile
Buffered streaming
Walk directories

os.ReadFile

os.ReadFile reads a whole file into memory in one call. It returns the bytes and an error, so check the error first. For small configs and notes this single call is all you need. Larger files deserve streaming, which comes later in this lesson.

package main import ( "fmt" "os" ) func main() { data, err := os.ReadFile("notes.txt") if err != nil { fmt.Println(err) return } fmt.Print(string(data)) }

The path is relative to the working directory of the running program. A missing file shows up as an error, not as empty data. Convert the bytes to a string only when you plan to print or parse text.

os.WriteFile

os.WriteFile writes bytes to a path in one call and creates the file when it is missing. The last argument sets permission bits, and 0644 is the usual default. One call replaces the whole file, which keeps small saves simple. For big reports switch to a buffered writer instead.

package main import ( "fmt" "os" ) func main() { text := []byte("hello, files\n") if err := os.WriteFile("hello.txt", text, 0644); err != nil { fmt.Println(err) return } fmt.Println("written") }

go run main.go

written

Buffered streaming

bufio adds buffering around readers and writers so small reads do not turn into many slow system calls. Scanner splits input into lines with almost no setup. Always check scan errors after the loop ends. The pattern below counts lines in files of any size.

package main import ( "bufio" "fmt" "os" ) func main() { in, err := os.Open("big.txt") if err != nil { fmt.Println(err) return } defer in.Close() scanner := bufio.NewScanner(in) count := 0 for scanner.Scan() { count++ } if err := scanner.Err(); err != nil { fmt.Println(err) return } fmt.Println(count) }

defer closes the file when main returns, even on the error paths above. Scanner work happens line by line, so memory stays flat. Writers get the same treatment with bufio.NewWriter plus Flush at the end.

Walk directories

filepath.WalkDir visits every entry under a directory tree. The callback runs once per file and folder, top down. Return an error from the callback to stop the walk early. Skipping directories keeps the output focused on real files.

package main import ( "fmt" "io/fs" "path/filepath" ) func main() { err := filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if !d.IsDir() { fmt.Println(path) } return nil }) if err != nil { fmt.Println(err) } }

The callback receives the path, the entry, and any error met on the way down. Handle that error inside the callback or the walk cannot continue past broken links. WalkDir reads lazily, so huge trees do not flood memory.

Next: HTTP servers

Article author: Arthur Isaev

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: