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

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

You can join more than 2 path elements.

On Windows the join above produces dir\sub\file.txt. On Unix and macOS it produces dir/sub/file.txt.

Get the file name

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

Split list of paths

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

Split a path into a directory and a file

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

Get directory name from path

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

Get file extension

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

Feedback about page:

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



Table Of Contents