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.

  • If the given new path already exists and it is not in a directory, then this method will replace it. But OS-specific restrictions may apply when the given old path and the new path are in different directories.
  • If the given path is incorrect, then it will throw an error of type *LinkError.
  • It is defined under the os package so, you have to import os package in your program for accessing Remove() function.

Syntax:

func Rename(old_path, new_path string) error

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
      
}

chevron_right


Output:

Before:



before renaming and moving a file in default directory in golang

After:

after renaming and moving a file in default directory in golang

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

Before:

before renaming and moving a file in default directory in golang

After:

after renaming and moving a file in default directory in golang




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.