Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

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

Posted on February 22, 2023April 16, 2023 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)
}
}

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

©2023 Welcome To Golang By Example | Design: Web XP