Parsing a text file by characters

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

I’m new to Godot and wish to parse a file by characters. The file can be quite large so I’d prefer not reading the whole thing as a string. So far I have this:

var file = File.new()
file.open(filename, File.READ)
while !file.eof_reached():
    var character = char(file.get_8())
    if !file.eof_reached():
        print(character) # here I would call my parser

Without the if inside the while the last character is always garbage since the EOF is only reached after executing file.get_8(). As far as I know there is no do while loop in GDscript, so is there a better way to achieve this?

:bust_in_silhouette: Reply From: Artium Nihamkin

This is subjective, but I always prefer for loops over while loop. A habit I acquired working in the embedded area.

var file = File.new()
file.open("res://test.txt", File.READ)
for _ in range(file.get_len() - 1):
	print(file.get_8())

Sometimes the “for” version does not look that nice and compact, but it always guaranteed to terminate.

Your suggestion certainly looks more elegant, but _ as variable name isn’t accepted, so I had to replace it to something else, like i. Other than this it’s working perfectly. Thank you!

Wabbitseason | 2018-01-01 22:43