Welcome To Golang By Example

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

Move file from one location to another in or command mv in Go (Golang)

Posted on February 22, 2020April 16, 2020 by admin

os.Rename() function can be used to mv or move a file from one location to another. It is equivalent to command ‘mv’ of Linux. Below is the signature of the function

func Rename(oldpath, newpath string) error

Code:

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

    newLocation := "~/Desktop/temp.txt"
    err = os.Rename("temp.txt", newLocation)
    if err != nil {
        log.Fatal(err)
    }
}
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