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.
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. 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!