# GoDot 4.4.1 Stable
#
# Call / Execute function with:
# var mylist = _buildPathContents("C:/my/path/to/some/directory")
#
# [ Example Output ]
# for _key in mylist :
# print(_key)
# for i in range(mylist[_key].size()):
# print("\t" + mylist[_key][i])
#
func _buildPathContents(_path: String, _tempfiletree: Dictionary = {}) -> Dictionary:
# Print files/directories into console window (only if GoDot is running Debug Mode)
var _printDebug = false
# Open path so we can view contents
var _dir = DirAccess.open(_path)
# Check if we gained access to the path
if _dir:
# Make sure we have a key to append files into
if not _tempfiletree.has(_path):
_tempfiletree[_path] = []
# Begin iterating
_dir.list_dir_begin()
# Get first file or directory
var _filename = _dir.get_next()
# Loop as long as we have a name for something
while _filename != "":
if _dir.current_is_dir():
if OS.is_debug_build() and _printDebug:
print("Dir: " + _filename)
# Call self for subdirectory
_tempfiletree = _buildPathContents(_path.path_join(_filename), _tempfiletree)
else:
# Add file to array
_tempfiletree[_dir.get_current_dir()].append(_filename)
if OS.is_debug_build() and _printDebug:
print("File: " + _filename)
# Get next file or directory
_filename = _dir.get_next()
# End iterating
_dir.list_dir_end()
return _tempfiletree
You can make it a coroutine in-case you need to sync the exchange:
Call with:
var mylist = await _buildPathContents("C:/my/path/to/some/directory")
Change
_tempfiletree = _buildPathContents(_path.path_join(_filename), _tempfiletree)
To:
_tempfiletree = await _buildPathContents(_path.path_join(_filename), _tempfiletree)
It is not ‘proper’ but it works and works well, use for any number of file-tree tasks. With some alteration, customize to only return specific files or file types even.