How to write a list of lists in a txt file?

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

+4
source share
5 answers

Pickle will work, but the disadvantage is that it is a binary format specific to Python. Save as JSON for readability and reuse in other applications:

import json

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

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

Now the file contains:

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

To return it later:

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

print newList
+9
source

To save it:

import cPickle

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

To return it:

import cPickle

savefilePath = 'path/to/file'
with open(savefilePath) as savefile:
  myBigList = cPickle.load(savefile)
+6
source

. , . "" . , python. @inspectorG4dget , .

0

pickle, , , csv 16 , numpy.

import numpy as np

# here I use list of 3 lists as an example
nlist = 3

# generating fake data `listoflists`
listoflists = []
for i in xrange(3) :
    listoflists.append([i]*500)

# save it into a numpy array
outarr = np.vstack(listoflists)
# save it into a file
np.savetxt("test.dat", outarr.T)
0

cPickle , "" :

  • ZLIB.
  • .

:

  • ZLIB will reduce its size.
  • Encryption may continue to reset hijras.

Yes, the brine is not safe! See this.

0
source

All Articles