How to Rename and Move a File in Golang?


In Golang, renaming and moving files can be accomplished using the os and path/filepath packages. Renaming a file simply requires changing the name of the file, while moving a file involves changing its path. In this article, we'll explore how to rename and move a file in Golang.

Renaming a File in Golang

To rename a file in Golang, we can use the os.Rename function, which takes two arguments: the current file path and the new file path. Here's an example −

package main

import (
   "fmt"
   "os"
)

func main() {
   err := os.Rename("old.txt", "new.txt")
   if err != nil {
      fmt.Println(err)
      return
   }
   fmt.Println("File renamed successfully.")
}

In this example, we're renaming the file old.txt to new.txt. If the rename operation fails, we print the error message to the console. If the operation is successful, we print a success message to the console.

Moving a File in Golang

Moving a file in Golang is similar to renaming a file, except that we need to specify a new path for the file. We can use the path/filepath package to construct the new path based on the current directory and the desired destination directory. Here's an −

package main

import (
   "fmt"
   "os"
   "path/filepath"
)

func main() {
   currentDir, err := os.Getwd()
   if err != nil {
      fmt.Println(err)
      return
   }
   
   sourcePath := filepath.Join(currentDir, "old.txt")
   destDir := filepath.Join(currentDir, "new_directory")
   destPath := filepath.Join(destDir, "new.txt")
   
   err = os.MkdirAll(destDir, os.ModePerm)
   if err != nil {
      fmt.Println(err)
      return
   }
   
   err = os.Rename(sourcePath, destPath)
   if err != nil {
      fmt.Println(err)
      return
   }
   fmt.Println("File moved successfully.")
}

In this example, we're moving the file old.txt to a new directory called new_directory and renaming it to new.txt. We first get the current directory using os.Getwd(), and then use filepath.Join to construct the source and destination paths. We also create the destination directory using os.MkdirAll to ensure that the directory exists before we move the file. Finally, we use os.Rename to move the file to its new location.

Conclusion

In this article, we've learned how to rename and move a file in Golang using the os and path/filepath packages. Renaming a file is a simple operation that involves changing the name of the file, while moving a file requires changing its path. By understanding these concepts and the functions provided by Golang, you can easily perform these operations in your own projects.

Updated on: 25-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements