+1 vote

Hi I'm looking to load a plain text file that has lines of text (conversations) into a dictionary. So for example, I have these lines in a .txt file (each could be separated by a new line)

This is line one.

This is line two.

So I'd want to be able to load these into a dict and end up with { "1":"This is line one." , "2":"This is line two." } and have the keys just be the line numbers so I can reference them using dict["1"], etc.

I can load a text file into a dictionary using parse_json but I had to preformat those lines manually first, obviously not ideal.

How would I go about doing something like this? Thanks.

in Engine by (153 points)

1 Answer

+5 votes
Best answer

This can be achieved using the get_line() member function on the File class. An example (untested).

func load_file(filename):
  var result = {}
  var f = File.new()
  f.open(filename)
  var index = 1
  while not f.eof_reached():
    var line = f.get_line()
    result[str(index)] = line
    index += 1
  f.close()
by (325 points)
selected by

This is good, but the syntax is File.new(), not new File(), I believe.

Oops, sorry, you're quite right, edited. That's the problem with jumping between GDScript and other languages.

Thank you very much, works perfectly.

thanks man, this is a great help

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.