Golang – Find absolute path of a file.

This recipe finds the absolute path of the specified filename, the problem with this code is that it returns the first match and hence only useful if the filename is unique.

package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
)

var absPath string // global variable to store absolute path of filename.

func findFileAbsPath(basepath, filename string) (string, error) {
	// This function finds the absolute path of specified filename, returns the absolute path filename and error.
	// The function takes in a base path to search from, filepath.Walk searches file recursively.
	fileErr := filepath.Walk(basepath, func(path string, info os.FileInfo, err error) error {
		// path is the absolute path.
		if err != nil {
			return err
		}
		if info.Name() == filename {
			// if the filename is found return the absolute path of the file.
			absPath = path
		}
		return nil
	})
	if fileErr != nil {
		return "", fileErr
	}
	return absPath, nil
}

func main() {
// usage example.
	var err error
	absPath, err = findFileAbsPath("E:\\PythonProject", "test.py")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(absPath)
}

To list all absolute paths of the same filename change the absPath to []string, here’s a little modification of the original code.

package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
)

var absPath []string // global variable to store absolute path of filename.

func findFileAbsPath(basepath, filename string) ([]string, error) {
	// This function finds the absolute path of specified filename, returns the absolute path filename and error.
	// The function takes in a base path to search from, filepath.Walk searches file recursively.
	fileErr := filepath.Walk(basepath, func(path string, info os.FileInfo, err error) error {
		// path is the absolute path.
		if err != nil {
			return err
		}
		for {
			if info.Name() == filename {
				// if the filename is found append the path to the string slice.
				absPath = append(absPath, path)
			}
			break
		}

		return nil
	})
	if fileErr != nil {
		return []string{}, fileErr
	}
	return absPath, nil
}

func main() {
	var err error
	absPath, err = findFileAbsPath("E:\\PythonProject", "test.py")
	if err != nil {
		log.Fatal(err)
	}
	for _, path := range absPath {
		fmt.Println(path)
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s