rename a file in go

To rename a file in Go, you can use the os.Rename() function which takes two string arguments: the old file path and the new file path. Here's an example:

main.go
package main

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

func main() {
    oldFilePath := "/path/to/old/file.txt"
    newFilePath := "/path/to/new/file.txt"
    
    err := os.Rename(oldFilePath, newFilePath)
    if err != nil {
        fmt.Println("Error renaming file:", err)
        return
    }
    
    fmt.Println("File renamed successfully!")
}
360 chars
21 lines

In the above example, we first define the old file path (oldFilePath) and the new file path (newFilePath). We then call os.Rename() with these two paths as arguments. If the rename operation is successful, it will return nil, otherwise it will return an error.

Note that the os.Rename() function will also move the file if the new file path is in a different directory than the old file path. If you need to specify a new filename in the same directory as the old file, you can use the filepath.Join() function to construct the new file path:

main.go
newFilePath := filepath.Join(filepath.Dir(oldFilePath), "newfile.txt")
71 chars
2 lines

This will create a new file path with the same directory as the old file and with the new filename "newfile.txt".

gistlibby LogSnag