Extracting File Name from File Path in Go
Query: A developer encounters an issue while trying to extract the file name from a string containing both the file name and its path. The code that was attempted produces an unexpected numeric value rather than the desired base file name.
Explanation: The code utilizes the strings.LastIndex function to determine the index of the last slash character in the string. However, to obtain the file's base name, a different approach is required.
Solution: To effectively separate the file name from the path, the filepath.Base function should be employed. This function is specifically designed to return the base file name, excluding any preceding path elements.
Code Example:
path := "/some/path/to/remove/file.name" file := filepath.Base(path) fmt.Println(file)
Playground: http://play.golang.org/p/DzlCV-HC-r.
By leveraging the filepath.Base function, the developer can effortlessly extract the base file name from the provided path string, resulting in the desired output.
The above is the detailed content of How to Extract a Filename from a File Path in Go?. For more information, please follow other related articles on the PHP Chinese website!