File path operations

suggest change

Unfortunately different operating systems have different rules about the format of file paths.

For example, on Unix and Mac OS, path separator character is / and on Windows it’s \.

For portable programs, it’s important to use functions in filepath package that understand conventions used by a given operating system.

Note: filepath package manages OS file paths. There’s also path package with similar functionality but it always uses / as path separator.

Join a path

main.go

	path := filepath.Join("dir", "sub", "file.txt")
	fmt.Printf("path: %s\n", path)

Output:

path: dir/sub/file.txt

You can join more than 2 path elements.

On Windows the above would return dir\file.txt, on Unix and Mac OS it would return dir/file.txt.

Split a path into a directory and file

main.go

	path := filepath.Join("dir", "file.txt")
	file := filepath.Base(path)
	fmt.Printf("path: %s, file: %s\n", path, file)

Output:

path: dir/file.txt, file: file.txt

Split list of paths

main.go

	parts := filepath.SplitList("/usr/bin:/tmp")
	fmt.Printf("parts: %#v\n", parts)

Output:

parts: []string{"/usr/bin", "/tmp"}

Get file name from path

main.go

	path := filepath.Join("dir", "file.txt")
	dir, file := filepath.Split(path)
	fmt.Printf("dir: %s, file: %s\n", dir, file)

Output:

dir: dir/, file: file.txt

Get directory name from path

main.go

	path := filepath.Join("dir", "file.txt")
	dir := filepath.Dir(path)
	fmt.Printf("path: %s, dif: %s\n", path, dir)

Output:

path: dir/file.txt, dif: dir

Get file extension

main.go

	ext := filepath.Ext("file.txt")
	fmt.Printf("ext: %s\n", ext)

Output:

ext: .txt

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents