find the name of a file in go

To find the name of a file in Go, we can use the path/filepath package which provides various utilities for working with file paths.

We can use the Base function from this package which will return the last element of the path or the file name alone.

Here's an example code snippet:

main.go
package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    // Provide a file path
    file := "/path/to/file.txt"

    // Get the file name using filepath.Base
    fileName := filepath.Base(file)

    fmt.Println("File name:", fileName)
}
254 chars
17 lines

In the above code, we have provided a file path and used the filepath.Base function to get the file name. The fmt package is used to print the file name to the console.

Output:

main.go
File name: file.txt
20 chars
2 lines

gistlibby LogSnag