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 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) } }
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) } }
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") }
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!