Go Lesson 29 – File Handling| Dataplexa

File Handling in Go

In this lesson, you will learn how to work with files in Go. File handling is a critical skill for building real-world applications such as log processors, configuration loaders, data pipelines, and backend services.

Go provides a clean and powerful standard library to read, write, append, and manage files efficiently.


Why File Handling Is Important

Almost every production application interacts with files in some way.

  • Reading configuration files
  • Writing logs and reports
  • Processing CSV or JSON data
  • Saving application output

Understanding file handling allows you to build reliable and maintainable systems.


Importing Required Packages

Go uses the os and io packages for file operations.

import (
    "fmt"
    "os"
)

Creating a File

To create a new file, use os.Create(). If the file already exists, it will be truncated.

file, err := os.Create("report.txt")
if err != nil {
    fmt.Println("Error creating file:", err)
    return
}
defer file.Close()

The defer statement ensures the file is closed properly.


Writing Data to a File

You can write text data using WriteString().

content := "Daily Sales Report\nTotal Sales: 12500\n"
file.WriteString(content)

This is useful for logs, reports, and text-based outputs.


Appending to a File

To append data instead of overwriting, open the file with flags.

file, err := os.OpenFile(
    "report.txt",
    os.O_APPEND|os.O_CREATE|os.O_WRONLY,
    0644,
)
if err != nil {
    fmt.Println(err)
    return
}
defer file.Close()

file.WriteString("New Entry Added\n")

Reading a File Entirely

To read the full contents of a file, use os.ReadFile().

data, err := os.ReadFile("report.txt")
if err != nil {
    fmt.Println("Error reading file:", err)
    return
}

fmt.Println(string(data))

This approach works well for small to medium-sized files.


Reading Files Line by Line

For large files, reading line by line is more memory efficient.

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

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

Real-World Example: Log Processor

Imagine reading application logs to detect errors.

file, _ := os.Open("app.log")
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    line := scanner.Text()
    if strings.Contains(line, "ERROR") {
        fmt.Println("Found error:", line)
    }
}

File Permissions Explained

File permissions define who can read, write, or execute a file.

  • 0644 – Owner can read/write, others can read
  • 0755 – Executable files

Understanding permissions is essential when deploying applications.


Handling File Errors Safely

Always check errors when working with files.

if err != nil {
    fmt.Println("Operation failed:", err)
}

Best Practices for File Handling

  • Always close files using defer
  • Use buffered reading for large files
  • Check permissions before deployment
  • Avoid hardcoding file paths

Practice Exercises

Exercise 1

Create a file named data.txt and write sample text.

Exercise 2

Read the file and print its contents.

Exercise 3

Append new data without deleting old content.


What’s Next?

In the next lesson, you will learn about Working with JSON in Go and how to serialize and deserialize structured data.