Load files from directory

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Karl Wilhelm

I have an AnimatedSprite node, in which I want to load all .png files from a folder, and add them as frames. So before I can add them as frames I try to use this code to create a list of all files. But when I run this code, it only returns an endless stream of “Found dir: .”, which I assume is the current directory?

extends AnimatedSprite

func _ready():
	dir_contents('res://assets/planets')

func dir_contents(path):
	var dir = Directory.new()
	if dir.open(path) == OK:
		dir.list_dir_begin()
		var file_name = dir.get_next()
		
		while file_name != "":
			if dir.current_is_dir():
				print('Found dir: ' + file_name)
			else:
				print('Found file: ' + file_name)
		file_name = dir.get_next()
	else:
		print("An error occurred when trying to access the path.")
1 Like
:bust_in_silhouette: Reply From: Lopy

file_name = dir.get_next() is one indentation level to high, which means file_name does not change inside the loop.

“.” is indeed the current folder. You can use list_dir_begin(true) to skip it, along with “…” (parent folder).

Oh, that is such an embarrassing mistake! Thank you for your help, it works now, of course!

Karl Wilhelm | 2020-12-27 22:05

This code works well for me and supports loading resources in exported builds

func get_all_in_folder(path):
	var items = []
	var dir = DirAccess.open(path)
	if not dir:
		push_error("Invalid dir: " + path)
		return items  # Return an empty list if the directory is invalid

	# print("Opening directory: ", path)
	dir.list_dir_begin()
	var file_name = dir.get_next()
	while file_name != "":
		# print("Found file: ", file_name)
		if !file_name.begins_with(".") and !file_name.ends_with(".import"):
			var full_path = path + "/" + file_name
			# Remove .remap extension if present
			if full_path.ends_with(".remap"):
				full_path = full_path.substr(0, full_path.length() - 6)
			# print("Checking path: ", full_path)
			if ResourceLoader.exists(full_path):
				# print("Path exists: ", full_path)
				var res = ResourceLoader.load(full_path)
				if res:
					# print("Loaded resource: ", full_path)
					items.append(res)
				else:
					push_error("Failed to load resource: ", full_path)
			else:
				push_error("Resource does not exist: ", full_path)
		file_name = dir.get_next()
	dir.list_dir_end()
	return items
2 Likes

Thank you! Just what I was looking for and posted up only 15 hours ago! :slight_smile: