Working with the File System in Go: A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with the File System in Go: From Basics to Advanced Techniques



Go (Golang) is a modern programming language known for its simplicity and high performance. One of the key tasks any developer faces is working with the file system. In this article, we will thoroughly examine how to create, read, write files, manage directories, and handle paths in Go. You will get practical code examples that will help you master file operations quickly and efficiently.



Core Packages for File System Operations



In Go, file system operations are concentrated in three main packages of the standard library:

  • os — basic operations: opening, creating, deleting files and directories.
  • io and io/ioutil — reading and writing data (in newer versions of Go, it is recommended to use os instead of ioutil).
  • path/filepath — working with paths: joining, splitting, getting extensions.


Before starting, make sure you have imported the necessary packages:

package main

import ( "fmt" "os" "io" "path/filepath")


Reading and Writing Files in Go



Reading an Entire File

The simplest way to read a file is to use the os.ReadFile function (available since Go 1.16). It returns a byte slice and an error.

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


Writing to a File

To write data to a file, use os.WriteFile. If the file does not exist, it will be created. If it exists, it will be overwritten.

func writeFileExample() {    content := []byte("Hello, world!Second line.")    err := os.WriteFile("output.txt", content, 0644)    if err != nil {        fmt.Println("Error writing:", err)        return    }    fmt.Println("File successfully written")}


Reading Large Files Line by Line

For processing large files, it is better to use buffered reading to avoid loading the entire file into memory.

import "bufio"

func readLineByLine() { file, err := os.Open("large_file.txt") if err != nil { fmt.Println("Error opening:", err) return } defer file.Close()

scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Println("Error scanning:", err) }}


Working with Directories in Go



Creating and Deleting Directories

Use os.Mkdir to create a single directory, and os.MkdirAll for nested ones.

func createDirectories() {    // Create a single folder    err := os.Mkdir("mydir", 0755)    if err != nil {        fmt.Println("Error creating folder:", err)    }

// Create a nested structure err = os.MkdirAll("path/to/nested/dir", 0755) if err != nil { fmt.Println("Error creating nested folders:", err) }}


Deleting directories is done with os.Remove (for empty ones) and os.RemoveAll (for non-empty ones).

func removeDirectories() {    // Delete an empty folder    err := os.Remove("mydir")    if err != nil {        fmt.Println("Error deleting:", err)    }

// Delete a folder with all its contents err = os.RemoveAll("path/to") if err != nil { fmt.Println("Error recursive deletion:", err) }}


Reading Directory Contents

The os.ReadDir function returns a list of entries in a directory.


                
                

Blogs

Book Recommendations