How to rename and move a file in go

Sep 2, 2018 22:43 · 84 words · 1 minute read

To rename a file there is os.Rename method, which takes original name and the new name.

package main

import (
    "fmt"
    "os"
)

func main() {
    oldname := "file1.txt"
    newname := "file2.txt"
    err := os.Rename(oldname, newname)
    if err != nil {
        fmt.Println(err)
    }
}

The same method can be used to move the file as well.

package main

import (
    "fmt"
    "os"
)

func main() {
    originalPath := "file1.txt"
    newPath := "/some/other/folder/file2.txt"
    err := os.Rename(originalPath, newPath)
    if err != nil {
        fmt.Println(err)
    }
}