2

I am new at Python and I dont know what would be the best way to approuch this problem: I want to save nested lists in python as strings in a text file and then be able to load the information from the text file.

I would like to do something like that keeping in mind that the list and the dic are two random examples, the solution needs to be general.

This is how I would save it:


list = ["29", "24", "33", "34", ["25", "2" ,"3", "14", "79"], ["0", "26"]]
dict = {'A' : ["25", "2" ,"3", "14", "79"], 'B' : ["0", "26"], 'C' : ["0", "26", "33"]}
f = open("doc.txt","w")
f.write(str(dict)+"\n")
f.write(str(list))
f.close()

Then I would like to read the lines of the text file and load back the information they store like that but with the correct data type.

f = open("doc.txt","r")
content = f.read()
dic, list = content.split("\n")
f.close()
  • You probably want to look into the [json](https://docs.python.org/3/library/json.html) module, which does exactly what you want, as long as you're trying to save/load "simple" objects, such as lists, dicts, numbers, booleans, strings, ... – Mike Scotty Jul 04 '19 at 23:43
  • yep json.dumps and json.loads is what I needed – Daniel Casasampera Jul 05 '19 at 00:11

1 Answers1

2

JSON is the simplest solution and will work perfectly for simple data types. But you shall only store one "object", thus you need to combine the dict and the list by probably putting it in a single "outer" list.

To save:

outer_list = [your_dict, your_list]
with open(FILEPATH, "wb") as jsonfile:
    json.dump(outer_list, jsonfile)

To load:

with open(FILEPATH, "rb") as jsonfile:
    outer_list = json.load(jsonfile)
    your_dict, your_list = outer_list

I mentioned that it works with simple data types. If you wanted to store "non-simple" object such as your own defined class object, then you will probably need pickle (https://docs.python.org/3/library/pickle.html) to save it as binary rather than string. The API to save and load is similar.

Kevin Winata
  • 443
  • 2
  • 10
  • Thank you very much for the info, I actually build the hole thing to work with input strings so I wont be needing pickle, that said I didnt know you could save your own class objects so thanks for the info. – Daniel Casasampera Jul 05 '19 at 10:23