Go file programs read, write and manage files on disk, such as saving a report, loading a config or counting lines in a log. In this post, you will write fourteen file programs with their exact output, and every program explains its logic step by step in the code comments. We finish with the file programs interviewers ask most, such as counting words in a file and finding the longest line.
This post starts Level 5 of our Go programs series. It uses error handling from our Go error handling programs and the input tools from our Go user input programs. For the theory, read the Go file handling guide. All programs were tested on Go 1.27.
What are Go File Programs?
Go file programs use the os, bufio and io packages to create, read, change and delete files. A file is opened, used and then closed, and every step can return an error that you must check.
Think of a file like a notebook in a cupboard. You open the cupboard (open the file), read or write pages, and then put the notebook back and close the door (close the file). If you forget to close it, other people may not be able to use it.
Why Go File Programs Matter
Almost every backend program touches files. For example, a service reads a config file at start-up, a job writes a daily CSV report and a tool scans log files for errors. So Go file programs are a practical skill you will use every week.
- Configs and data: load settings, templates and seed data.
- Reports: write CSV or text files for other teams.
- Logs: read big log files line by line without loading them into memory.
- Interviews: count lines, words and characters is a classic coding task.
How Go File Programs Work
Most file work follows four steps. First, open or create the file and check the error. Next, read or write data. Then close the file, usually with defer. Finally, handle any error from the read, write or close.

The table below lists the file tools in this post.
| Task | Function | Good for |
|---|---|---|
| Write a whole file | os.WriteFile | Small files in one go |
| Read a whole file | os.ReadFile | Small files that fit in memory |
| Open for reading | os.Open | Reading step by step |
| Create or truncate | os.Create | Writing a new file |
| Append | os.OpenFile with O_APPEND | Adding to logs |
| Read line by line | bufio.Scanner | Big files |
| Copy | io.Copy | Any size, low memory |
| File info | os.Stat | Size, time, exists or not |
Basic Go File Programs
These first Go file programs write and read whole files. Each program works in a temporary folder, so it is safe to run anywhere, including the Go Playground.
Program 1: Your First File Program
package main
import (
"fmt" // fmt prints text on the screen
"os" // os works with files and folders
"path/filepath" // filepath builds file paths
)
func main() {
// Step 1: make a temporary folder so we never touch your real files.
// err is the error value. It is nil (empty) when nothing went wrong.
folder, err := os.MkdirTemp("", "first")
if err != nil {
fmt.Println("folder error:", err)
return
}
defer os.RemoveAll(folder) // defer runs this when main ends, so the folder is deleted
// Step 2: create a new, empty file inside the folder.
path := filepath.Join(folder, "hello.txt")
file, err := os.Create(path)
if err != nil {
fmt.Println("create error:", err)
return
}
// Step 3: write one line, then close the file.
file.WriteString("Hello, file!\n")
file.Close()
// Step 4: read the file back and print what is inside.
data, err := os.ReadFile(path)
if err != nil {
fmt.Println("read error:", err)
return
}
fmt.Print("File says: ", string(data)) // string() turns bytes into text
}
File says: Hello, file!
First, you make a safe temporary folder and create hello.txt inside it. Then you write one line and close the file. Finally, os.ReadFile reads the bytes back, and string() turns them into text you can print.
Program 2: Write and Read a Whole File
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// Make a temporary folder so we never touch real files.
folder, err := os.MkdirTemp("", "demo")
if err != nil {
fmt.Println("mkdir error:", err)
return
}
defer os.RemoveAll(folder) // clean up the folder when main ends
// filepath.Join builds a correct path on any OS.
path := filepath.Join(folder, "notes.txt")
// Step 1: write the whole file at once.
// []byte(...) turns the text into bytes, which files store.
// 0644 = owner can read and write, others can only read.
err = os.WriteFile(path, []byte("Learn Go\nWrite code\n"), 0644)
if err != nil {
fmt.Println("write error:", err)
return
}
// Step 2: read the whole file back into memory.
data, err := os.ReadFile(path)
if err != nil {
fmt.Println("read error:", err)
return
}
fmt.Print(string(data))
fmt.Println("Bytes:", len(data)) // len counts the bytes
}
Learn Go
Write code
Bytes: 20
os.WriteFile creates the file if needed and replaces any old content. os.ReadFile returns bytes, so we convert them to a string to print. The file has 20 bytes, because each \n new line also counts as one byte.
Program 3: Append Lines to a Log File
package main
import (
"fmt"
"os"
"path/filepath"
)
// appendLine adds one line to the end of a file.
func appendLine(path, line string) error {
// O_APPEND: always write at the end.
// O_CREATE: create the file if it does not exist.
// O_WRONLY: open for writing only.
// The | sign joins the three options together.
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close() // close the file when this function returns
_, err = file.WriteString(line + "\n")
return err
}
func main() {
// The _ ignores the error here to keep the demo short.
folder, _ := os.MkdirTemp("", "logs")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "app.log")
// Each call adds one line without removing old lines.
messages := []string{"server started", "user login", "server stopped"}
for _, message := range messages {
err := appendLine(path, message)
if err != nil {
fmt.Println("error:", err)
}
}
data, _ := os.ReadFile(path)
fmt.Print(string(data))
}
server started
user login
server stopped
The appendLine function opens the file with three flags joined by |. Then it writes one line at the end. Without O_APPEND, each write would start at the beginning of the file.
Program 4: Check if a File Exists
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
// exists returns true if the file is there, and false if it is missing.
func exists(path string) bool {
// os.Stat returns file info, or an error if something is wrong.
_, err := os.Stat(path)
// fs.ErrNotExist means the file is simply missing.
if errors.Is(err, fs.ErrNotExist) {
return false
}
return true
}
func main() {
folder, _ := os.MkdirTemp("", "check")
defer os.RemoveAll(folder)
configPath := filepath.Join(folder, "config.json")
os.WriteFile(configPath, []byte("{}"), 0644)
missingPath := filepath.Join(folder, "missing.json")
fmt.Println("config.json:", exists(configPath))
fmt.Println("missing.json:", exists(missingPath))
}
config.json: true
missing.json: false
os.Stat asks the system about the file. We check the error with errors.Is, as in our error handling post. Other errors, such as “permission denied”, mean the file may exist but we cannot see it.
Line-by-Line Go File Programs
Big files can be gigabytes in size. These Go file programs read one line at a time, so memory use stays tiny.
Program 5: Read a File Line by Line
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "read")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "cities.txt")
os.WriteFile(path, []byte("Pune\nDelhi\nGoa\n"), 0644)
file, err := os.Open(path) // open for reading only
if err != nil {
fmt.Println("open error:", err)
return
}
defer file.Close()
// Scanner reads one line per Scan() call.
scanner := bufio.NewScanner(file)
lineNumber := 0
for scanner.Scan() { // the loop stops when there are no more lines
lineNumber++
fmt.Printf("%d: %s\n", lineNumber, scanner.Text()) // %d is a number, %s is text
}
// Always check for a read error after the loop.
err = scanner.Err()
if err != nil {
fmt.Println("scan error:", err)
}
}
1: Pune
2: Delhi
3: Goa
bufio.NewScanner wraps the open file. Each Scan call moves to the next line, and scanner.Text() gives the line without the new line character. The final scanner.Err() check catches problems like a broken disk.
Program 6: Add Up Numbers Stored in a File
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strconv"
)
func main() {
folder, _ := os.MkdirTemp("", "expenses")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "expenses.txt")
os.WriteFile(path, []byte("120\n45\nabc\n300\n"), 0644)
file, err := os.Open(path)
if err != nil {
fmt.Println("open error:", err)
return
}
defer file.Close()
total := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Step 1: turn the text into a number. Atoi means "ASCII to integer".
amount, err := strconv.Atoi(line)
if err != nil {
fmt.Println("Skipped, not a number:", line)
continue // jump to the next line
}
// Step 2: add the number to the running total.
total += amount
fmt.Println("Added", amount)
}
fmt.Println("Total spent:", total)
}
Added 120
Added 45
Skipped, not a number: abc
Added 300
Total spent: 465
The scanner reads one line at a time, just like in Program 5. Then strconv.Atoi turns each line into a number. If a line is not a number, continue skips it, so one bad line does not stop the whole sum.
Program 7: Copy a File with io.Copy
package main
import (
"fmt"
"io"
"os"
"path/filepath"
)
// copyFile copies the source file into the target file and returns the bytes copied.
func copyFile(source, target string) (int64, error) {
sourceFile, err := os.Open(source)
if err != nil {
return 0, err
}
defer sourceFile.Close()
targetFile, err := os.Create(target) // creates or empties the target
if err != nil {
return 0, err
}
defer targetFile.Close()
// io.Copy moves data in small chunks, so even huge files use little memory.
return io.Copy(targetFile, sourceFile)
}
func main() {
folder, _ := os.MkdirTemp("", "copy")
defer os.RemoveAll(folder)
source := filepath.Join(folder, "report.txt")
target := filepath.Join(folder, "backup.txt")
os.WriteFile(source, []byte("Q3 sales: 4.2 lakh"), 0644)
copiedBytes, err := copyFile(source, target)
fmt.Println("copied bytes:", copiedBytes, "error:", err)
data, _ := os.ReadFile(target)
fmt.Println(string(data))
}
copied bytes: 18 error: <nil>
Q3 sales: 4.2 lakh
copyFile opens the source for reading and creates the target for writing. Then io.Copy moves the bytes from one to the other. The error prints as <nil>, which means the copy worked.
Program 8: File Size and Info
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "info")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "photo.txt")
os.WriteFile(path, []byte("1234567890"), 0644)
// os.Stat returns facts about the file, such as its name and size.
info, err := os.Stat(path)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Name:", info.Name())
fmt.Println("Size:", info.Size(), "bytes")
fmt.Println("Is folder:", info.IsDir())
fmt.Println("Mode:", info.Mode()) // the read and write permissions
}
Name: photo.txt
Size: 10 bytes
Is folder: false
Mode: -rw-r--r--
os.Stat gives you an info value with small methods for each fact. Mode shows the permissions we passed as 0644. The modification time also lives in info.ModTime(), but we skip it because it changes every run.
Folder and CSV Go File Programs
These Go file programs work with folders and spreadsheet-style data.
Program 9: List Files in a Folder
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "list")
defer os.RemoveAll(folder)
// Create a few files and one sub-folder.
for _, name := range []string{"b.txt", "a.go", "c.csv"} {
os.WriteFile(filepath.Join(folder, name), []byte("x"), 0644)
}
os.Mkdir(filepath.Join(folder, "images"), 0755)
// os.ReadDir returns entries already sorted by name.
entries, err := os.ReadDir(folder)
if err != nil {
fmt.Println(err)
return
}
for _, entry := range entries {
kind := "file"
if entry.IsDir() {
kind = "folder"
}
fmt.Println(entry.Name(), "-", kind)
}
}
a.go - file
b.txt - file
c.csv - file
images - folder
First, the program creates three files and one folder. Then os.ReadDir returns every entry, sorted by name. For each entry, IsDir tells you whether it is a folder or a file.
Program 10: Write and Read a CSV File
package main
import (
"encoding/csv"
"fmt"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "csv")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "students.csv")
// Step 1: write the rows. Each row is a list of text cells.
file, _ := os.Create(path)
writer := csv.NewWriter(file)
rows := [][]string{{"name", "marks"}, {"Asha", "91"}, {"Ravi, Jr", "78"}}
writer.WriteAll(rows) // WriteAll also flushes the buffer
file.Close()
// Step 2: open the file again and read every row.
file, _ = os.Open(path)
defer file.Close()
records, err := csv.NewReader(file).ReadAll()
if err != nil {
fmt.Println(err)
return
}
// records[1:] means "all rows from index 1", so it skips the header row.
for _, record := range records[1:] {
fmt.Printf("%s scored %s\n", record[0], record[1])
}
}
Asha scored 91
Ravi, Jr scored 78
“Ravi, Jr” has a comma inside, so the CSV writer wraps it in quotes. The reader removes the quotes again. That is why you should never split CSV lines with strings.Split.
Program 11: Delete a File Safely
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "del")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "temp.txt")
os.WriteFile(path, []byte("bye"), 0644)
// The first remove works, so the error is nil.
fmt.Println("first remove:", os.Remove(path))
// Removing again fails, because the file is already gone.
err := os.Remove(path)
fmt.Println("second remove is not-exist:", errors.Is(err, fs.ErrNotExist))
}
first remove: <nil>
second remove is not-exist: true
os.Remove deletes the file and returns nil on success. The second call fails, because the file is gone. With errors.Is, you can tell “already deleted” apart from real problems.
Most Asked Interview Go File Programs
These Go file programs are the ones interviewers ask most often.
Program 12: Count Lines, Words and Characters
This is the Go version of the Unix wc command.
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"unicode/utf8"
)
func main() {
folder, _ := os.MkdirTemp("", "wc")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "story.txt")
os.WriteFile(path, []byte("Go is simple\nGo is fast\n\nGo is fun\n"), 0644)
file, _ := os.Open(path)
defer file.Close()
lines := 0
words := 0
chars := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
lines++ // every Scan is one line
words += len(strings.Fields(line)) // Fields splits on spaces
chars += utf8.RuneCountInString(line) // count characters, not bytes
}
fmt.Println("Lines:", lines, "Words:", words, "Chars:", chars)
}
Lines: 4 Words: 9 Chars: 31
The scanner gives one line at a time, and each line adds one to lines. strings.Fields splits the line into words, so we add how many it found. The empty third line still counts as a line, but it adds no words.
Program 13: Find the Longest Line
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "long")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "log.txt")
os.WriteFile(path, []byte("ok\nerror: disk almost full\nwarn: slow\n"), 0644)
file, _ := os.Open(path)
defer file.Close()
longest := "" // the longest line seen so far
longestNumber := 0 // its line number
current := 0 // the line we are reading now
scanner := bufio.NewScanner(file)
for scanner.Scan() {
current++
line := scanner.Text()
// Keep the line only if it is longer than the best so far.
if len(line) > len(longest) {
longest = line
longestNumber = current
}
}
// %q prints the text inside double quotes.
fmt.Printf("Line %d is longest: %q (%d chars)\n", longestNumber, longest, len(longest))
}
Line 2 is longest: "error: disk almost full" (23 chars)
The program remembers the longest line and its number. For each new line, it compares the length with the best so far. If the new line is longer, it becomes the new best.
Program 14: Word Frequency from a File
package main
import (
"bufio"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
)
func main() {
folder, _ := os.MkdirTemp("", "freq")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "words.txt")
os.WriteFile(path, []byte("Go go GO\nrust Go\n"), 0644)
file, _ := os.Open(path)
defer file.Close()
// A map links each word to how many times we saw it.
count := map[string]int{}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords) // one word per Scan, not one line
for scanner.Scan() {
word := strings.ToLower(scanner.Text()) // ignore upper and lower case
count[word]++
}
// Map order is random, so sort the keys before printing.
for _, word := range slices.Sorted(maps.Keys(count)) {
fmt.Println(word, count[word])
}
}
go 4
rust 1
bufio.ScanWords changes the scanner to return words. Each word is made lower case and counted in the map. Combined, this is the standard answer to “count words in a file”.
ReadFile vs bufio.Scanner in Go File Programs
Go file programs have two main ways to read a file. The diagram and table below compare them.

| Feature | os.ReadFile | bufio.Scanner |
|---|---|---|
| Reads | Whole file at once | One line or word at a time |
| Memory | Equal to file size | Small, about 64 KB buffer |
| Code length | One line | A short loop |
| Big files (1 GB+) | Risky | Safe |
| Best for | Configs, small files | Logs, large data |
So use os.ReadFile for small files and bufio.Scanner for anything that might grow large.
Common Mistakes in Go File Programs
- Forgetting to close: every
os.Openoros.Createneeds aClose, usually withdefer. - Ignoring errors: a missing file or bad permission shows up only in the error value.
- os.Create on an existing file: it empties the file first, so use
O_APPENDto add lines. - Building paths with +: use
filepath.Join, which uses the right slash for each OS. - Splitting CSV by commas: quoted fields break, so use
encoding/csv.
Best Practices for Go File Programs
- Use defer f.Close() right after a successful open.
- Read big files with bufio, never all at once.
- Use 0644 for files and 0755 for folders, which are the common safe defaults.
- Use os.MkdirTemp in tests, so tests never touch real user files.
- Check scanner.Err() after every scanning loop.
Go File Programs Interview Questions and Answers
Interviewers ask these Go file programs more than any other file questions. Each program is complete, with real output from Go 1.27.
Read and Write Questions
Q1. What is the difference between os.Create and os.OpenFile?
os.Create opens a file for writing, creates it if needed, and empties it if it exists. os.OpenFile lets you choose flags such as O_APPEND, O_RDONLY or O_EXCL, so you control exactly what happens.
Q2. What does 0644 mean?
It is a file permission in octal. The owner can read and write (6), and the group and others can only read (4 and 4). Folders often use 0755, so others can also open them.
Q3. What does this program print?
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "q3")
defer os.RemoveAll(folder)
path := filepath.Join(folder, "a.txt")
os.WriteFile(path, []byte("first"), 0644)
os.WriteFile(path, []byte("second"), 0644) // replaces, does not append
data, _ := os.ReadFile(path)
fmt.Println(string(data))
}
second
os.WriteFile always replaces the content. To keep “first”, open the file with O_APPEND.
Q4. What does this program print?
package main
import (
"fmt"
"os"
)
func main() {
_, err := os.ReadFile("does-not-exist.txt")
fmt.Println(err)
}
open does-not-exist.txt: no such file or directory
The error includes the operation, the path and the reason. That is why Go file errors are easy to debug.
Buffer and Performance Questions
Q5. Why use bufio.Writer for many small writes?
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "buf")
defer os.RemoveAll(folder)
file, _ := os.Create(filepath.Join(folder, "nums.txt"))
defer file.Close()
writer := bufio.NewWriter(file) // collects writes in memory first
for i := 1; i <= 1000; i++ {
fmt.Fprintln(writer, i) // Fprintln prints into the writer, not the screen
}
fmt.Println("buffered bytes before flush:", writer.Buffered() > 0)
writer.Flush() // write everything to the file in one go
info, _ := file.Stat()
fmt.Println("file size:", info.Size())
}
buffered bytes before flush: true
file size: 3893
Each Fprintln goes into memory, and Flush writes the whole buffer at once. If you forget Flush, the last part of your data is lost.
Q6. What is the default line limit of bufio.Scanner?
About 64 KB per line (bufio.MaxScanTokenSize). For longer lines, call scanner.Buffer with a bigger buffer, or use bufio.Reader.ReadString instead.
Q7. Why should you defer Close right after the error check?
If you defer before checking the error, you may call Close on a nil file. If you defer much later, an early return can skip it and leak the file handle.
Path and Folder Questions on Go File Programs
Q8. What does this program print?
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := filepath.Join("data", "2026", "report.csv")
// Base is the file name, Ext is the extension, Dir is the folder part.
fmt.Println(filepath.Base(path), filepath.Ext(path), filepath.Dir(path))
}
report.csv .csv data/2026
On Windows, Dir would show data\2026, because filepath uses the right separator for each OS.
Q9. How do you create nested folders?
Use os.MkdirAll("logs/2026/oct", 0755). It creates every missing folder on the path and does nothing if they already exist.
Q10. How do you walk every file under a folder?
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
)
func main() {
folder, _ := os.MkdirTemp("", "walk")
defer os.RemoveAll(folder)
os.MkdirAll(filepath.Join(folder, "src", "util"), 0755)
os.WriteFile(filepath.Join(folder, "src", "main.go"), nil, 0644)
os.WriteFile(filepath.Join(folder, "src", "util", "str.go"), nil, 0644)
// WalkDir visits every file and folder in name order.
// It calls this small function once for each entry it finds.
filepath.WalkDir(folder, func(path string, entry fs.DirEntry, err error) error {
if !entry.IsDir() { // ! means "not", so this skips folders
relativePath, _ := filepath.Rel(folder, path) // path inside our folder
fmt.Println(relativePath)
}
return nil // nil means "keep walking"
})
}
src/main.go
src/util/str.go
filepath.WalkDir goes through every folder level for you. For each entry, the small function skips folders and prints files. filepath.Rel cuts off the temporary folder part, so the output stays short.
Q11. How do you embed a file into your Go binary?
Use the embed package with a //go:embed config.json comment above a string, []byte or embed.FS variable. The file then ships inside the binary, so you do not need it on disk at run time.
Q12. Is os.ReadFile safe for a 2 GB log file?
No. It loads all 2 GB into memory, which can crash small servers. Use bufio.Scanner or io.Copy so only a small part is in memory at a time.
Practice Task
This task combines several Go file programs from above. Write a program that reads a log file and writes only the lines containing “ERROR” into a new file called errors.log, then prints how many lines it copied. Hint: open the source with os.Open, the target with os.Create, and use bufio.Scanner with strings.Contains.
Official Resources
Quick Recap
- Go file programs open, read or write, and close files, checking every error.
os.WriteFileandos.ReadFileare simple for small files.bufio.Scannerreads big files line by line with little memory.- Use
O_APPENDto add to a file, becauseos.Createempties it. - Use
filepath.Join,encoding/csvanddefer Closefor safe, portable code.
What’s Next?
Next, we turn Go data into JSON and back. Read Go JSON programs with output, with marshal, unmarshal, nested JSON and struct tags. For the theory, see the Go file handling guide.


