Renaming files is a common task in programming, and with Golang, it can be done easily. Golang provides a simple and efficient way to rename files within a directory, as well as move and rename them to a new directory. In this article, we will learn how to rename files using Golang and explore different use cases for this functionality. Whether you need to organize files in your file system, automate file renaming tasks, or build a tool that requires file renaming, Golang makes it simple and efficient. So, let’s dive into the world of Golang file renaming!

Rename file in golang

Example

Renaming files can be a necessary task when working with files in a project. Whether you’re renaming a file for organizational purposes or to update its name, it can be done easily with Golang. In this article, we’ll take a look at a simple example of how to rename an existing file using Golang. Before running the program, make sure that the file you want to rename already exists in the specified directory. If the file does not exist, you can simply create an empty file with the desired name.

package main

import "os"

func main() {
  // source and destionation name
  src := "hello.txt"
  dst := "golang.txt"

  // rename file
  os.Rename(src, dst)
}

Run the program with the command:

go run rename.go

The file will be renamed to a new file. ### Rename in shell Now there are other ways to do this, for example on a Linux or Mac OS X system you can run the command

mv source.txt destination.txt

But this may or may not work on other platforms. Thats why you should always use the modules provides by the programming language.

Exercises

  • Which package has the rename function?