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.
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
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.
1 A file rename or moved successfully !!
Read non-existing file
1 package main
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "log"
7 )
8
9 func main() {
10
11
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.
1 open text.txt: no such file or directory
2 exit status 1
Related options for your search