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
+8.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+5.7k Unix/Linux : How to test user agents blocked successfully ?
+4.5k Mac OSX : Get disk partitions' size, type and name
+22k Golang : Match strings by wildcard patterns with filepath.Match() function
+36.4k Golang : Display float in 2 decimal points and rounding up or down
+16.9k Golang : Covert map/slice/array to JSON or XML format
+10.2k Golang : cannot assign type int to value (type uint8) in range error
+3.5k Java : Get FX sentiment from website example
+8.1k Swift : Convert (cast) Character to Integer?
+6.7k Mac/Linux/Windows : Get CPU information from command line
+12k Golang : Get remaining text such as id or filename after last segment in URL path
+17.1k Google Chrome : Your connection to website is encrypted with obsolete cryptography