Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a list of lists into a txt file?

Tags:

python

I have a list of 16 elements, and each element is another 500 elements long. I would like to write this to a txt file so I no longer have to create the list from a simulation. How can I do this, and then access the list again?

like image 358
Demetri Pananos Avatar asked Dec 07 '22 04:12

Demetri Pananos


2 Answers

Pickle will work, but the shortcoming is that it is a Python-specific binary format. Save as JSON for easy reading and re-use in other applications:

import json

LoL = [ range(5), list("ABCDE"), range(5) ]

with open('Jfile.txt','w') as myfile:
    json.dump(LoL,myfile)

The file now contains:

[[0, 1, 2, 3, 4], ["A", "B", "C", "D", "E"], [0, 1, 2, 3, 4]]

To get it back later:

with open('Jfile.txt','r') as infile:
    newList = json.load(infile)

print newList
like image 189
beroe Avatar answered Dec 28 '22 02:12

beroe


To store it:

import cPickle

savefilePath = 'path/to/file'
with open(savefilePath, 'w') as savefile:
  cPickle.dump(myBigList, savefile)

To get it back:

import cPickle

savefilePath = 'path/to/file'
with open(savefilePath) as savefile:
  myBigList = cPickle.load(savefile)
like image 27
inspectorG4dget Avatar answered Dec 28 '22 01:12

inspectorG4dget