File Paths in GDScript

The OS class in GDScript provides functions to work with file paths in a way that is portable between operating systems. Here’s how you can use it:

extends Node

func _ready():
    # join_paths should be used to construct paths in a
    # portable way. It takes any number of arguments
    # and constructs a hierarchical path from them.
    var p = OS.join_paths("dir1", "dir2", "filename")
    print("p: ", p)

    # You should always use join_paths instead of
    # concatenating "/" manually. In addition
    # to providing portability, join_paths will also
    # normalize paths by removing superfluous separators
    # and directory changes.
    print(OS.join_paths("dir1//", "filename"))
    print(OS.join_paths("dir1/../dir1", "filename"))

    # get_base_dir and get_file can be used to split a path to the
    # directory and the file.
    print("Dir(p): ", OS.get_base_dir(p))
    print("Base(p): ", OS.get_file(p))

    # We can check whether a path is absolute.
    print(OS.is_abs_path("dir/file"))
    print(OS.is_abs_path("/dir/file"))

    var filename = "config.json"

    # Some file names have extensions following a dot. We
    # can split the extension out of such names.
    var ext = filename.get_extension()
    print(ext)

    # To find the file's name with the extension removed,
    # use get_basename.
    print(filename.get_basename())

    # get_relative_path finds a relative path between a base and a
    # target. It returns an empty string if the target cannot
    # be made relative to base.
    var rel = OS.get_relative_path("a/b", "a/b/t/file")
    print(rel)

    rel = OS.get_relative_path("a/b", "a/c/t/file")
    print(rel)

To run this script, save it as a .gd file and attach it to a Node in your Godot scene. The output will be printed to the Godot output panel.

Note that GDScript doesn’t have exact equivalents for all the Go filepath functions, but the OS class provides similar functionality for working with file paths. The String class in GDScript also offers some useful methods for working with file names and paths.

Remember that in GDScript, paths use forward slashes ("/") regardless of the operating system, which simplifies some operations compared to Go’s filepath package.

GDScript doesn’t have a direct equivalent to Go’s error handling, so error checking is omitted in this translation. In a real Godot project, you might want to add additional checks or use GDScript’s built-in debugging functions for more robust error handling.