Get number of lines in txt file?

Godot Version

4.4beta1

Question

Hello, I would just like to know how to get the amount of lines in a txt file to randomize which line gets output. That’s all.

a line is defined by the character “\n”, which is a newline.

a script has to take the file as text (in the case of godot, a String), then (in godot) it can be broken into an Array of String wherever there’s a newline character.
finally, you can count the number of items of the array, that is the number of lines.

var text_file_path = "res://text_folder/my_text_file.txt"

func read_text() -> void:
	var file = FileAccess.open(text_file_path, FileAccess.READ)
	var contents = file.get_as_text()
	var text_file_contents : PackedStringArray = contents.split("\n", true)
	print(text_file.size())
2 Likes