File Paths in Miranda

Here’s the translation of the Go code to Python, along with explanations in Markdown format suitable for Hugo:

The os.path module provides functions to parse and construct file paths in a way that is portable between operating systems; dir/file on Linux vs. dir\file on Windows, for example.

import os
import os.path

def main():
    # os.path.join should be used to construct paths in a
    # portable way. It takes any number of arguments
    # and constructs a hierarchical path from them.
    p = os.path.join("dir1", "dir2", "filename")
    print("p:", p)

    # You should always use os.path.join instead of
    # concatenating '/'s or '\'s manually. In addition
    # to providing portability, join will also
    # normalize paths by removing superfluous separators
    # and directory changes.
    print(os.path.join("dir1//", "filename"))
    print(os.path.join("dir1/../dir1", "filename"))

    # os.path.dirname and os.path.basename can be used to split a path to the
    # directory and the file. Alternatively, os.path.split will
    # return both in the same call.
    print("dirname(p):", os.path.dirname(p))
    print("basename(p):", os.path.basename(p))

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

    filename = "config.json"

    # Some file names have extensions following a dot. We
    # can split the extension out of such names with os.path.splitext.
    name, ext = os.path.splitext(filename)
    print(ext)

    # To find the file's name with the extension removed,
    # we can use the name part from splitext.
    print(name)

    # os.path.relpath finds a relative path between a base and a
    # target. It returns an error if the target cannot
    # be made relative to base.
    rel = os.path.relpath("a/b/t/file", "a/b")
    print(rel)

    rel = os.path.relpath("a/c/t/file", "a/b")
    print(rel)

if __name__ == "__main__":
    main()

To run the program, save it as file_paths.py and use python:

$ python file_paths.py
p: dir1/dir2/filename
dir1/filename
dir1/filename
dirname(p): dir1/dir2
basename(p): filename
False
True
.json
config
t/file
../c/t/file

In this Python version:

  1. We use the os.path module which provides similar functionality to Go’s filepath package.
  2. os.path.join is used instead of filepath.Join.
  3. os.path.dirname and os.path.basename replace filepath.Dir and filepath.Base.
  4. os.path.isabs is used instead of filepath.IsAbs.
  5. os.path.splitext is used to get the file extension, replacing filepath.Ext.
  6. os.path.relpath is used instead of filepath.Rel.

Note that Python’s os.path module doesn’t throw exceptions for operations like relpath, so we don’t need to handle errors in the same way as the Go code.