EZ

Eduzan

Learning Hub

Back to GO PROGRAMMING LANGUAGE

File Handling (Input/Output) in Go (Golang)

Published 2025-12-16

Go Programming Language

Introduction to File Handling

File handling refers to the process of creating, reading, writing, updating, and deleting files stored on a computer’s file system. In Go, file handling is part of standard input/output (I/O) operations and is handled mainly using the os, io, and bufio packages.

File handling allows programs to:

  • Store data permanently
  • Read configuration files
  • Process logs
  • Handle large datasets
  • Exchange data between programs

Packages Used for File Handling in Go

Go provides powerful built-in packages for file I/O:

File Handling (Input/Output) in Go (Golang)
PackagePurpose
osFile creation, opening, deleting
ioLow-level I/O primitives
bufioBuffered I/O (efficient reading/writing)
fmtFormatted input/output
ioutil (deprecated)Older file utilities (replaced by os & io)

Creating a File in Go

Using os.Create()

os.Create() creates a new file.
If the file already exists, it truncates (clears) the file.

package main

import (
	"os"
)

func main() {
	file, err := os.Create("example.txt")
	if err != nil {
		panic(err)
	}
	defer file.Close()
}

Explanation

  • Returns a file pointer
  • Must always close the file
  • defer file.Close() ensures cleanup

Opening an Existing File

Using os.Open()

Used for read-only access.

file, err := os.Open("example.txt")
if err != nil {
	panic(err)
}
defer file.Close()

Using os.OpenFile()

Allows full control over file access modes.

file, err := os.OpenFile(
	"example.txt",
	os.O_APPEND|os.O_CREATE|os.O_WRONLY,
	0644,
)

File Flags

File Handling (Input/Output) in Go (Golang)
FlagMeaning
os.O_RDONLYRead only
os.O_WRONLYWrite only
os.O_RDWRRead & write
os.O_CREATECreate if not exists
os.O_APPENDAppend to file
os.O_TRUNCTruncate file

Writing to a File

Writing Using WriteString()

file, _ := os.Create("data.txt")
defer file.Close()

file.WriteString("Hello, Go File Handling\n")

Writing Using fmt.Fprintln()

fmt.Fprintln(file, "This is a line written using fmt")

Writing Using bufio.Writer (Recommended)

Buffered writing is faster.

writer := bufio.NewWriter(file)
writer.WriteString("Buffered writing in Go\n")
writer.Flush()

Reading from a File

Reading Using os.ReadFile() (Simple)

data, err := os.ReadFile("example.txt")
if err != nil {
	panic(err)
}
fmt.Println(string(data))

Best for small files.


Reading Using bufio.Scanner (Line by Line)

file, _ := os.Open("example.txt")
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
	fmt.Println(scanner.Text())
}

Used for:

  • Log files
  • Text processing
  • Line-based input

Reading Using bufio.Reader

reader := bufio.NewReader(file)
line, _ := reader.ReadString('\n')
fmt.Println(line)

Appending to a File

Appending adds content without deleting existing data.

file, _ := os.OpenFile(
	"example.txt",
	os.O_APPEND|os.O_WRONLY,
	0644,
)
defer file.Close()

file.WriteString("New appended line\n")

Deleting a File

Use os.Remove().

err := os.Remove("example.txt")
if err != nil {
	panic(err)
}

Checking if a File Exists

if _, err := os.Stat("example.txt"); err == nil {
	fmt.Println("File exists")
} else {
	fmt.Println("File does not exist")
}

Getting File Information

Use os.Stat().

info, _ := os.Stat("example.txt")

fmt.Println("Name:", info.Name())
fmt.Println("Size:", info.Size())
fmt.Println("Permissions:", info.Mode())
fmt.Println("Modified:", info.ModTime())

File Permissions in Go

Permissions use Unix-style notation.

File Handling (Input/Output) in Go (Golang)
ValueMeaning
0644Owner read/write, others read
0755Executable permissions
0600Owner only

Handling Errors in File I/O

Error handling is critical in Go.

file, err := os.Open("missing.txt")
if err != nil {
	fmt.Println("Error:", err)
	return
}

Go forces explicit error checking, improving reliability.


Copying File Contents

source, _ := os.Open("a.txt")
defer source.Close()

destination, _ := os.Create("b.txt")
defer destination.Close()

io.Copy(destination, source)

Reading User Input and Writing to File

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
input, _ := reader.ReadString('\n')

file, _ := os.Create("user.txt")
defer file.Close()

file.WriteString(input)

File Handling Best Practices

  • Always close files
  • Use defer
  • Prefer buffered I/O
  • Handle errors properly
  • Avoid reading large files fully into memory

Common Mistakes in Go File Handling

  • Forgetting file.Close()
  • Ignoring errors
  • Using deprecated ioutil package
  • Overwriting files unintentionally
  • Not flushing buffered writers

Practical Example: Log File Writer

file, _ := os.OpenFile("log.txt",
	os.O_APPEND|os.O_CREATE|os.O_WRONLY,
	0644)

defer file.Close()

log := bufio.NewWriter(file)
log.WriteString("Application started\n")
log.Flush()

Summary

  • Go provides robust file I/O using os, io, and bufio
  • Supports file creation, reading, writing, appending, and deletion
  • Explicit error handling ensures safety
  • Buffered I/O improves performance
  • Essential for backend systems, CLI tools, and system programs