How to import and read text?

:bust_in_silhouette: Reply From: johnygames

Basically what you want to do is load a file and read its content. You can do that by placing a .txt file in your project folder. Then you store the file’s path in a variable named “file”. Then you need to open said file and do whatever you want with its content. The following example opens a specified file, goes though it line by line and prints out each line unitl the end of the file is reached.

extends Node2D

onready var file = 'res://foobar.txt'

func _ready():
	load_file(file)

func load_file(file):
	
	var f = File.new()
	f.open(file, File.READ)
	var index = 1
	while not f.eof_reached(): # iterate through all lines until the end of file is reached
		var line = f.get_line()
		line += " "
		print(line + str(index))

		index += 1
	f.close()
	return

Place the above code in your main node or wherever you think is necessary. I hope this helps.

This works, but when I export the project to Android, the text file isn’t bundled it seems and I get a read error :frowning:
The text file doesn’t have a corresponding .import file and I’m not sure how to create one… Not sure if that’s the reason why it doesn’t get bundled in the final APK.

endavid | 2022-03-20 21:03

When I get to the get_line, it comes back with a NULL value after a bit of a pause. The file is big (360M), could this be too big for this function to read?

var line = f.get_line()

grymjack | 2023-01-11 01:37

1 Like