Go (Golang) / File Handling and I/O Operations

Working with Directories and File Paths

This tutorial will guide you through working with directories and file paths in Go. We will cover creating, reading, renaming, and deleting directories, as well as handling file p…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explains how to read and write files, work with directories, and handle I/O operations in Go.

1. Introduction

In this tutorial, we aim at familiarizing you with the handling of directories and file paths in Go. The Go programming language, also known as Golang, provides a robust set of libraries and features for managing directories and file paths. We will be exploring how to create, read, rename, and delete directories, as well as how to manipulate file paths.

By the end of this tutorial, you will be able to:

  • Create, read, rename, and delete directories in Go.
  • Work with file paths effectively, such as joining paths, finding the base name, and extracting the directory part.

Prerequisites:

  • Basic knowledge of Go programming language.
  • An installed Go environment to run code snippets.

2. Step-by-Step Guide

The os and filepath packages in Go provide a variety of functions to work with directories and file paths. Here's an overview:

  • os.Mkdir(): Creates a new directory.
  • os.MkdirAll(): Creates a new directory, including any necessary parents.
  • os.ReadDir(): Reads the directory named by dirname and returns a list of directory entries.
  • os.Rename(): Renames (moves) a file or directory.
  • os.Remove(): Removes a file or directory.
  • filepath.Join(): Joins any number of path elements into a single path.
  • filepath.Base(): Returns the last element of a path.
  • filepath.Dir(): Returns all but the last element of a path.

3. Code Examples

Creating a Directory

package main

import (
    "log"
    "os"
)

func main() {
    // Create a new directory called "exampledir"
    err := os.Mkdir("exampledir", 0755)
    if err != nil {
        log.Fatal(err)
    }

    log.Println("Directory created")
}

In the above code, os.Mkdir function is used to create a new directory named "exampledir". The second parameter, 0755, is the permission that the directory should have. If the directory is successfully created, it logs "Directory created".

Reading a Directory

package main

import (
    "fmt"
    "io/fs"
    "os"
)

func main() {
    files, err := os.ReadDir(".")
    if err != nil {
        fmt.Println(err)
    }

    for _, file := range files {
        fmt.Println(file.Name())
    }
}

This code reads the current directory (denoted by ".") and prints out the names of all files and directories in it.

4. Summary

This tutorial covered how to work with directories and file paths in Go. We learned how to create, read, rename, and delete directories. We also explored how to join paths, find the base name, and extract the directory part of a path.

For further learning, you can explore the official Go documentation and other resources on working with files and directories in Go.

5. Practice Exercises

  1. Exercise: Write a Go program to create a directory named "testdir", create a file named "testfile.txt" inside it, and write "Hello, World!" into the file.

  2. Exercise: Write a Go program to read the contents of the "testdir" directory and print the names and sizes of all files in it.

  3. Exercise: Write a Go program to rename the "testdir" directory to "newdir" and delete the "testfile.txt" file in it.

Solutions:

  1. Solution:
package main

import (
    "log"
    "os"
)

func main() {
    // Create a directory
    err := os.Mkdir("testdir", 0755)
    if err != nil {
        log.Fatal(err)
    }

    // Create a file
    file, err := os.Create("testdir/testfile.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // Write to the file
    _, err = file.WriteString("Hello, World!")
    if err != nil {
        log.Fatal(err)
    }
}
  1. Solution:
package main

import (
    "fmt"
    "os"
)

func main() {
    files, err := os.ReadDir("testdir")
    if err != nil {
        fmt.Println(err)
    }

    for _, file := range files {
        fileInfo, _ := file.Info()
        fmt.Printf("Name: %s, Size: %d\n", file.Name(), fileInfo.Size())
    }
}
  1. Solution:
package main

import (
    "log"
    "os"
)

func main() {
    // Rename the directory
    err := os.Rename("testdir", "newdir")
    if err != nil {
        log.Fatal(err)
    }

    // Delete the file
    err = os.Remove("newdir/testfile.txt")
    if err != nil {
        log.Fatal(err)
    }
}

Remember, practice makes perfect! Keep coding and exploring different ways to work with directories and file paths in Go.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Time Zone Converter

Convert time between different time zones.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help