Go by Example: Directories

The Go standard library provides the os package for working with the file system, including directories. Here’s an example that demonstrates how to use the os package to work with directories:

package main

import (

func main() {
	// Create a new directory
	err := os.Mkdir("new_directory", 0700)
	if err != nil {
		fmt.Println("Error creating directory:", err)

	// Change to the new directory
	err = os.Chdir("new_directory")
	if err != nil {
		fmt.Println("Error changing to directory:", err)

	// Get the current working directory
	cwd, err := os.Getwd()
	if err != nil {
		fmt.Println("Error getting current working directory:", err)
	fmt.Println("Current working directory:", cwd)

	// Remove the directory
	err = os.Remove("new_directory")
	if err != nil {
		fmt.Println("Error removing directory:", err)

In this example, we use the os.Mkdir function to create a new directory named “new_directory”. The second argument to os.Mkdir is the permission mode for the directory.

We then use the os.Chdir function to change to the new directory.

The os.Getwd function returns the current working directory, which we use to check that we have indeed changed to the new directory.

Finally, we use the os.Remove function to remove the directory.


Leave a Reply

Your email address will not be published. Required fields are marked *