rename Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/rename/ Thu, 16 Apr 2020 09:15:33 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 rename Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/rename/ 32 32 159787465 Rename file or folder in Go (Golang) https://vikasboss.github.io/rename-file-folder-golang/ https://vikasboss.github.io/rename-file-folder-golang/#respond Wed, 15 Apr 2020 21:15:15 +0000 https://vikasboss.github.io/?p=2004 Overview os.Rename() function can be used to rename a file or folder. Below is the signature of the function. old and new can be fully qualified as well. If the old and...

The post Rename file or folder in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
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

The post Rename file or folder in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/rename-file-folder-golang/feed/ 0 2004