1

I am new to python and would like to export some nested lists and some variables in a .txt file in python, and to be able to retrieve these data and to import them later in python.

For instance,

my_list1 =  [[[-1, 1, 0, -1]], [[-1, 1, 0, -1]]]
my_list2 =   [[[2, 1, 1], [1, 1, 0, 2]], [[2, 1, 1, 0], [0, 2, 1, 1]]]
my_var = 3
my_var2 = 7

I tried

   with open("file.txt", "w") as f:
      for ( my_list1 , my_list2) in zip(my_list1 , my_list2 ):
         f.write("{1},{2}\n".format(my_list1 , my_list2))

but I don't know how to also export my variables with it, and how to import and retrieve each data after.

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mar
  • 187
  • 8
  • Take a look at [`pickle`](https://docs.python.org/3.6/library/pickle.html) – Bahrom Nov 08 '17 at 18:11
  • Possible duplicate of [Python save variable to file like save() in MATLAB](https://stackoverflow.com/questions/31915120/python-save-variable-to-file-like-save-in-matlab) – bendl Nov 08 '17 at 18:11
  • Possible duplicate of [Python serialization - Why pickle?](https://stackoverflow.com/questions/8968884/python-serialization-why-pickle) – Bahrom Nov 08 '17 at 18:12

1 Answers1

3

This might help:

import pickle

my_list1 =  [[[-1, 1, 0, -1]], [[-1, 1, 0, -1]]]
my_list2 =   [[[2, 1, 1], [1, 1, 0, 2]], [[2, 1, 1, 0], [0, 2, 1, 1]]]
my_var = 3
my_var2 = 7

# storing to file
with open("file.txt", 'wb') as f:
    pickle.dump((my_list1, my_list2, my_var, my_var2), f)

# loading from file
with open("file.txt", 'rb') as f:
    retrived_list1, retrived_list2, retrived_var, retrived_var2 = pickle.load(f)

print(retrived_list1 == my_list1, retrived_list2 == my_list2, retrived_var == my_var, retrived_var2 == my_var2)

Output:True True True True

tkhurana96
  • 919
  • 7
  • 25