Home  >  Article  >  Backend Development  >  Rename files using Go's Rename function

Rename files using Go's Rename function

WBOY
WBOYOriginal
2024-04-08 14:21:01884browse

The os.Rename function in the Go language can conveniently rename files or directories and update file or directory names without losing data. It takes two parameters: oldpath (current path) and newpath (new path). This function overwrites existing targets and can only rename files or directories in the same file system.

利用 Go 语言的 Rename 函数重命名文件

Use the Rename function of Go language to rename files

Introduction

Go The language's os.Rename function allows you to easily rename a file or directory. It provides a safe way to update the name of a file or directory without losing any data.

Syntax

func Rename(oldpath, newpath string) error
  • oldpath: The current path of the file to be renamed.
  • newpath: New file path.

Practical case

The following code snippet demonstrates how to use the Rename function to rename a file:

package main

import (
    "fmt"
    "os"
)

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

above In the example, we rename the file named "file.txt" to "new_file.txt". If the renaming is successful, the program will output "File renamed successfully". Otherwise, it will print an error message.

Note

  • Rename function will overwrite existing files or directories. If the target path already exists, it will be overwritten by the renamed file or directory.
  • If oldpath and newpath point to the same file, Rename will do nothing.
  • Rename Will not rename across file systems. It can only rename files or directories in the same file system.

The above is the detailed content of Rename files using Go's Rename function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn