0

I am trying to export a multi dimensional list to some external file and then later import the said list from that same external file to use in different program.

How do I go about doing this?

An example list would be something like this:

A=[[[1,1,1],[1,1,2]],
   [[1,2,1],[1,2,2],[1,2,3]],
   [[1,3,1]]]

It doesn't necessarily have to be a text file, if there any file type more suitable to what I am attempting let me know.

2
  • Try pickle Commented Jun 15, 2020 at 23:18
  • Please mark a preferred solution :) Commented Sep 14, 2020 at 12:18

2 Answers 2

1

You can use the built-in json package. When writing, you convert the data to a json string using json.dumps(), then you can read the data using json.loads().

import json

def writeList(file, data):
    with open(file, 'w') as f:
        f.write(json.dumps(data))

def readList(file):
    with open(file, 'r') as f:
        return json.loads(f.read())

if __name__ == '__main__':
    # File extension can be whatever you want
    A = [[[1,1,1],[1,1,2]], [[1,2,1],[1,2,2],[1,2,3]], [[1,3,1]]]
    filename = 'myfile.json'

    writeList(filename, A)
    print(readList(filename))
Sign up to request clarification or add additional context in comments.

Comments

0

By far the easiest method is to just pickle the object you want to save. This is a super easy way to save and load objects in python.

import pickle

A=[[[1,1,1],[1,1,2]],
   [[1,2,1],[1,2,2],[1,2,3]],
   [[1,3,1]]]

# Save the object
with open('filename.pkl', 'w'):
    pickle.dump(A, f)

It is as easily loaded when you need it

import pickle

with open('filename.pkl', 'rb') as f:
    B = pickle.load(f)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.