How do you get the file extension of a file

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By J.B Stepan

Im trying to read the extension of a file, is there a function like, get_extension(), or something like that?

:bust_in_silhouette: Reply From: exuin

No, but if you’re using a Directory to get files, you can get the file extension from the name of the file since it’s at the end of the name.

:bust_in_silhouette: Reply From: maddytroupe

once you get the full path to your file using directory, just use get_extension()
example below

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 directory: " + file_name)
else:
print("Found file: " + file_name)
file_name = dir.get_next()
print(file_name.get_extension())
else:
print(“An error occurred when trying to access the path.”)

func _on_Button_pressed():
dir_contents(“res://sounds/music”);

under scores have been removed in my above post. so please use correct functions
Thanks

maddytroupe | 2020-12-28 11:13

:bust_in_silhouette: Reply From: Toothgapsy

I am a bit late to the party - but for anyone stumbling across this via search engine: Godot Strings provide the exact wished functionality by now: String — Godot Engine (stable) documentation in English