Extended Expand Path Tutioral


bge.logic.expandPath can be extended to include user paths, custom working directories, and existence checks.




Place this code in a file called expandPath.py, contained in the same directory as the .blend.

def expandPath(path, workingPath=False, check=False):
  'https' = raise ValueError because bge doesn't seem to support https
  'http' = returns unmodified path
  '//' = working directory of the blend
  '/' = absolute path
  '~/' = user path
  '' = working directory supplied by workingPath
  if check is True and path dose not point to a file,
  a FileNotFoundError will be raised.
  import bge
  # https://docs.python.org/3/library/os.path.html#module-os.path
  import os.path
  if path.startswith('https'):  raise ValueError('Bge dose not seem to support https.  Try simply removing the s in the path.  Changing https:// to http://')
  # If its http, assume the path is not relative.
  elif path.startswith('http'):  return path
  if not path.startswith('/'):  #'//' and '/' are handled by the bge
    # Solve a user path.
    if path.startswith('~'):  path = os.path.expanduser(path)
    # Add the working path if supplied.
    elif workingPath:  path = workingPath+'/'+path
    # If nothing works raise an exception.
    else:  raise ValueError('The path '+path+' has an unrecognized prefix and no workingPath was supplied.')
  # If the path has already been solved than bge.logic.expandPath will leave it alone.
  path = bge.logic.expandPath(path)
  # Check to see if the file actaly exists.
  if check and not os.path.exists(path):  raise FileNotFoundError('The path '+path+' was not found.')
  return path


Edit this document to ask or answer questions.

Further Reading

String Methods

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License