Open In App

How to Rename and Move a File in Golang?

In the Go language, you are allowed to rename and move the existing file to a new path with the help of the Rename() method. This method is used to rename and move a file from the old path to the new path.

Syntax:



func Rename(old_path, new_path string) error

Example 1:




// Go program to illustrate how to rename
// and move a file in default directory
package main
    
import (
    "log"
    "os"
)
    
func main() {
   
    // Rename and Remove a file
    // Using Rename() function
    Original_Path := "GeeksforGeeks.txt"
    New_Path := "gfg.txt"
    e := os.Rename(Original_Path, New_Path)
    if e != nil {
        log.Fatal(e)
    }
      
}

Output:



Before:

After:

Example 2:




// Go program to illustrate how to rename 
// and remove a file in the new directory
package main
    
import (
    "log"
    "os"
)
    
func main() {
   
    // Rename and Remove a file
    // Using Rename() function
    Original_Path := "/Users/anki/Documents/new_folder/GeeksforGeeks.txt"
    New_Path := "/Users/anki/Documents/new_folder/myfolder/gfg.txt"
    e := os.Rename(Original_Path, New_Path)
    if e != nil {
        log.Fatal(e)
    }
}

Output:

Before:

After:


Article Tags :