Iterating through a folder and collecting every filename in that folder?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Robster
:warning: Old Version Published before Godot 3 was released.

Hi all,

I have a level editor I’ve setup. As I create new images I want to drop them into a folder, say called “sprites” and then press “refresh” in my editor and all the images are found, turned into sprites.

I think I can handle most of the bits surrounding that but I’m stuck on actually grabbing all the filenames in a folder.

Does anyone have a suggestion as to where I can research this further? I couldn’t find anything in the OS or file section of the docs that made sense to me regarding this.

Thanks so much…

:bust_in_silhouette: Reply From: avencherus

http://docs.godotengine.org/en/stable/classes/class_directory.html#description

You legend! There it was all along. Directory class. Thank you so much. That’s almost a copy/paste for what I’m after and it’s really simple to understand. Thanks again.

Robster | 2017-04-19 08:51

No problem. X)

avencherus | 2017-04-19 08:53

:bust_in_silhouette: Reply From: luna84

Godot 4 has removed the Directory class and added DirAccess

Here is the example code for iterating through a directory

func dir_contents(path):
var dir = DirAccess.open(path)
if dir:
    dir.list_dir_begin()
    var file_name = dir.get_next()
    while file_name != "":
        if dir.current_is_dir():
            print("Found directory: " + file_name)
        else:
            print("Found file: " + file_name)
        file_name = dir.get_next()
else:
    print("An error occurred when trying to access the path.")

Example value of the path variable could be following

path = "res://generate-tiles/assets/"