Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Rename file or folder in Go (Golang)

Posted on April 15, 2020April 16, 2020 by admin

Table of Contents

  • Overview
  • Code
    • Renaming a file
    • Renaming a folder

Overview

os.Rename() function can be used to rename a file or folder. Below is the signature of the function.

func Rename(old, new string) error


old and new can be fully qualified as well. If the old and new path doesn’t lie in the same directory then os.Rename() function behaves the same as moving a file or folder.

Code

Renaming a file

Below is code for renaming a file

package main

import (
    "log"
    "os"
)

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

    //Change permission so that it can be moved
    err = os.Chmod("temp.txt", 0777)
    if err != nil {
        log.Println(err)
    }


    err = os.Rename("temp.txt", "newTemp.txt")
    if err != nil {
        log.Fatal(err)
    }
}

Output

First, it will create a file named temp.txt in the current working directory. Then it will rename it to newTemp.txt

Renaming a folder

Below is code for renaming a folder

package main

import (
    "log"
    "os"
)

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

Output:

First it will create a folder named temp in current working directory. Then it will rename it to newTemp

  • file
  • folder
  • go
  • golang
  • rename
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme