How to Move or Rename a File in Go

1. Introduction

Moving or renaming a file is a common task in file system manipulation. In Go, the os package provides a simple and efficient way to perform this operation. This post will guide you through moving (or renaming) a file in Go using the os.Rename function.

Definition

In Go, moving or renaming a file is done using the os.Rename function, which changes the name or location of a file. It's important to note that os.Rename works within the same file system, but moving files across different file systems may require a different approach.

2. Program Steps

1. Use the os.Rename function to rename or move a file.

2. Handle any errors that occur during the operation.

3. Code Program

package main

import (
	"fmt"
	"os"
)

func main() {
	// Define the original and new file names
	originalPath := "old_name.txt"
	newPath := "new_name.txt"

	// Step 1: Rename or move the file
	err := os.Rename(originalPath, newPath)
	if err != nil {
		// Step 2: Handle errors
		fmt.Println("Error renaming/moving file:", err)
		return
	}

	fmt.Printf("File moved/renamed from %s to %s successfully.\n", originalPath, newPath)
}

Output:

File moved/renamed from old_name.txt to new_name.txt successfully.

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "os" - Importing the necessary packages for formatted output and operating system functionality.

3. originalPath and newPath variables are defined to hold the current and new file paths.

4. os.Rename is called with the old and new file paths to move or rename the file.

5. If os.Rename returns an error, it is printed to the console, and the program returns early.

6. If no error occurs, a success message is printed with fmt.Printf, indicating the file has been moved or renamed.

7. The output confirms the successful execution of the file move/rename operation.


Comments