How do I load a plain text file into a dictionary?

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

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.

:bust_in_silhouette: Reply From: pgregory

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()

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

Azai | 2018-02-26 11:37

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

pgregory | 2018-02-26 11:48

Thank you very much, works perfectly.

jobax | 2018-02-26 21:53

thanks man, this is a great help

Shlopynoobnoob | 2019-12-29 17:04