Go language file renaming guide

PHPz
Release: 2024-04-08 16:27:02
Original
517 people have browsed it

How to rename files in Go language? Use the os.Rename function, which accepts the old filename and the new filename as parameters. Use filepath.Join to join path elements and create a new file path. Practical case: Use the os.Rename function to rename the file named file1.txt to file2.txt, located in the data directory.

Go 语言文件重命名指南

Go Language File Renaming Guide

Renaming files is a common task for file operations in the Go language. This guide will introduce several effective ways to rename files, including practical examples.

Method 1: Using os.Rename

The os.Rename function is the primary method for renaming files. It accepts two parameters: old filename and new filename.

package main

import (
    "fmt"
    "os"
)

func main() {
    err := os.Rename("old-file.txt", "new-file.txt")
    if err != nil {
        fmt.Println(err)
    }
}
Copy after login

Method 2: Using filepath.Join

In some cases, you need to use the file path to rename the file. The filepath.Join function can be used to join path elements and create a new file path.

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    oldPath := "data/old-file.txt"
    newPath := "data/new-file.txt"
    err := os.Rename(oldPath, newPath)
    if err != nil {
        fmt.Println(err)
    }
}
Copy after login

Practical case

The following is a practical case showing how to use os.Rename to rename a file:

package main

import (
    "fmt"
    "os"
)

func main() {
    dir := "data"
    oldName := "file1.txt"
    newName := "file2.txt"

    // 检查是否存在要重命名的文件
    if _, err := os.Stat(filepath.Join(dir, oldName)); err != nil {
        fmt.Println("File not found")
        return
    }

    // 执行重命名操作
    err := os.Rename(filepath.Join(dir, oldName), filepath.Join(dir, newName))
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("File successfully renamed")
}
Copy after login

By following this guide, you can easily rename files in Go language.

The above is the detailed content of Go language file renaming guide. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template