Rename files with golang. Once you have a file in a directory you can simply rename it from your code.

The file will be renamed in the same directory. If you want to rename and move it to a new directory, change the variable to_file.

Related course: Introducing Go: Build Reliable, Scalable Programs

Rename file in golang

Example

The program below renames an existing file. Make sure the file exists before running the file. You can simply create an empty file.

1
2
3
4
5
6
7
8
9
10
11
12
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:

1
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

1
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?