Load variable from file

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

How to load variable from .csv-file?

:bust_in_silhouette: Reply From: godot_dev_

By doing a quick search of the forums using ‘file read write’ as a query, I found these posts should be a good starting point for you

The idea is to use the File API to read and write to a file. In your case , if you have a CSV file, every line will be ',' deliniated, so when reading the file line by line, you can use the split function (see String documentation) to seperate your line by ',' to access each variable’s value for the current row by iterating over the arrays elements. So something like the below:

var rowValues = line.split(",")
for value in rowValues:
    pass #process the CSV cell here 

An alternative to using the String classes split method, you can also use the FileAccess classes get_csv_line method. Both split and get_csv_line return a PackedStringArray, but using get_csv_line removes a small step.

Also, File was changed to FileAccess in Godot 4.x. So, look for that instead.

tuon | 2023-06-25 14:11

Thanks, I wasn’t aware!

godot_dev_ | 2023-06-25 14:58

Thats good. But how can i set value of the line that reading in the moment?

Lord_snow | 2023-06-25 16:56

I’m not sure what is being asked for, but if it’s an example of how to do it - here it is.

func _load_csv() -> void:
	var file = FileAccess.open("res://example.csv", FileAccess.READ)
	if file == null:
		printerr("Could not load example.csv: %s" % error_string(FileAccess.get_open_error()))
	print("begin processing csv data")

	# get header line - remove/comment next line if no header in csv file
	var _discarded_header_line = file.get_line()
	while !file.eof_reached():
		var csv_data := file.get_csv_line()
		# process csv data - for example just print it
		print("CSV data is %s" % ", ".join(csv_data))
	print("done processing csv data")

The contents of example.csv can be anything but as an example use


tuon | 2023-06-25 18:27

Thanks for everyone) the problem is solved

Lord_snow | 2023-06-26 14:33