Menu Close

Go – How to rename a file in go

Here, We will learn how to rename a file in go. We can do it by using Rename() function in os package in go golang. Rename() function either renames or moves old path to new path.

If there is a new path already exists and this path is not a directory then Rename() functions replaces it.

Function prototype:

func Rename(oldpath, newpath string) error

Return value:

Rename() function in os package returns 
an *LinkError, if any.

Example with code:

package main

import (



func main() {

  src_file_path := "sample.txt"

  dst_file_path := "golang.txt"

  os.Rename(src_file_path, dst_file_path)



$ ls -lrt *txt
-rw-r--r-- 1 John staff 16 May 18 19:33 sample.txt

$ go run sample.go

ls -lrt *txt
-rw-r--r-- 1 John staff 16 May 18 19:33 golang.txt

Note: sample.txt gets replaced by golang.txt

To learn more about golang, Please refer given below link:

Posted in golang, os, packages

Leave a Reply

Your email address will not be published. Required fields are marked *