Rename and move a file in Golang
To rename and move file in Go language can be achieved by using Rename() function. A Rename() function is provided in os package. It takes two parameters old path and new path including file name.
If newpath already exists and is not a directory, Rename replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories.
Syntax
 1 func os.Rename(oldpath string, newpath string) error
oldpath : A oldpath which need to rename or move, it includes path with file name and extension
newpath : A newpath where file needs to be rename or move, it includes path with file name and extension
Return : it returns either error if any or nil, if operation perform successfully
Rename or move file
 1 package main
 2 
 3 import (
 4 	"fmt"
 5 	"log"
 6 	"os"
 7 )
 8 
 9 func main() {
 10 	originalPath := "text.txt"
 11 	newPath := "textCopy.txt"
 12 
 13 	err := os.Rename(originalPath, newPath)
 14 
 15 	if err != nil {
 16 	   log.Fatal(err)
 17 	}
 18 
 19 	fmt.Println("A file rename or moved successfully !!")
 20 }
In the above example, we have define two path source and destination. It is specified as parameters to the Rename() function. If operation perform successfully, a file must be present at the newpath. If error occurred, it will print error otherwise success message.
Output
 1 A file rename or moved successfully !!

Read non-existing file

Read non-existing file
 1 package main
 2 
 3 import (
 4 	"fmt"
 5 	"io/ioutil"
 6 	"log"
 7 )
 8 
 9 func main() {
 10     
 11     // read non-existing file
 12 	content, err := ioutil.ReadFile("text.txt")
 13 
 14 	if err != nil {
 15 	   log.Fatal(err)
 16 	} else {
 17 	    fmt.Println(string(content))    
 18 	}
 19 }
In the above example, a file text.txt is specified to the ReadFile() function, it raise an error as specified file is rename to textCopy.txt. An error is printed using log module Fatal() function.
Output
 1 open text.txt: no such file or directory
 2 exit status 1
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us