Home > Article > Backend Development > Get the filename portion of a file path using the path/filepath.Base function
Use the path/filepath.Base function to obtain the file name part of the file path
Introduction:
When processing the file path, sometimes it is necessary to obtain the file name part of the file path for operation. In the Go language, you can use the Base function of the path/filepath package to implement this function. This article will introduce the use of Base function in detail and give corresponding code examples.
The definition and function of the Base function
The Base function is a function in the path/filepath package. Its definition is as follows:
func Base(path string) string
The function of the Base function is Extract the filename part from the file path. It returns everything after the last slash ("/" or "") in the path as a filename. If there are no slashes in the path, the entire path is returned.
How to use the Base function
Using the Base function is very simple. You only need to pass in the file path as a parameter to get the file name part. The following is a sample code using the Base function:
package main import ( "fmt" "path/filepath" ) func main() { path := "/home/user/documents/file.txt" filename := filepath.Base(path) fmt.Println("文件名:", filename) }
Run the above code, the output result is:
文件名: file.txt
In this example, we use a hard-coded file path "/home/ user/documents/file.txt", and used the Base function to obtain the file name "file.txt".
The following are some other sample codes to show the various uses of the Base function:
package main import ( "fmt" "path/filepath" ) func main() { path1 := "/home/user/documents/folder/" path2 := "C:\Program Files\Go\file.txt" path3 := "" path4 := "path/without/slash" fmt.Println("文件名1:", filepath.Base(path1)) fmt.Println("文件名2:", filepath.Base(path2)) fmt.Println("文件名3:", filepath.Base(path3)) fmt.Println("文件名4:", filepath.Base(path4)) }
The above codes correspond to the following four situations:
Summary:
You can easily get the file name part of the file path using the Base function of the path/filepath package of the Go language. It is one of the commonly used functions for processing file paths and is very useful during file operations. Through the introduction and sample code of this article, you have already understood the definition, usage and some precautions of the Base function. I hope it will help you get the file name part more conveniently when processing file paths.
The above is the detailed content of Get the filename portion of a file path using the path/filepath.Base function. For more information, please follow other related articles on the PHP Chinese website!