Golang : Move file to another directory
So far, Go does not have a function to directly move file to different folders. We have to provide our own method to do that.
First way is to use the os.Rename method. We are going to move a file \Folder_A\file.txt
to \Folder_B\file.txt
movefile.go
package main
import (
"fmt"
"os"
)
func main() {
err := os.Rename("\Folder_A\file.txt", "\Folder_B\file.txt")
if err != nil {
fmt.Println(err)
return
}
}
the second method is Copy file to target destination and Delete file at source. It was covered in this Copy file in Go tutorial. All you need to do is to specify the target destination and delete the file at source after copying.
See also : Golang : Rename file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.9k Golang : Error reading timestamp with GORM or SQL driver
+31.6k Golang : How to check if a date is within certain range?
+6.7k Golang : Rename part of filename
+6.1k Golang : Pat multiplexer routing example
+11.1k Golang : Save webcamera frames to video file
+9.9k Golang : Fix go.exe is not compatible with the version of Windows you're running
+50.9k Golang : How to get struct field and value by name
+12.3k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+6.3k Golang : How to iterate a slice without using for loop?
+7.6k PHP : How to parse ElasticSearch JSON ?
+9k Golang : List available AWS regions
+14.5k Golang : Validate hostname