如何将列表列表写入txt文件?

Dem*_*nos 4 python

我有一个包含16个元素的列表,每个元素是另外500个元素.我想将其写入txt文件,因此我不再需要从模拟中创建列表.我该怎么做,然后再次访问列表?

ber*_*roe 9

Pickle会起作用,但缺点是它是一种特定于Python的二进制格式.另存为JSON,便于在其他应用程序中阅读和重复使用:

import json

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

with open('Jfile.txt','w') as myfile:
    json.dump(LoL,myfile)
Run Code Online (Sandbox Code Playgroud)

该文件现在包含:

[[0, 1, 2, 3, 4], ["A", "B", "C", "D", "E"], [0, 1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)

稍后再回来:

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

print newList
Run Code Online (Sandbox Code Playgroud)


ins*_*get 6

存储它:

import cPickle

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

要取回它:

import cPickle

savefilePath = 'path/to/file'
with open(savefilePath) as savefile:
  myBigList = cPickle.load(savefile)
Run Code Online (Sandbox Code Playgroud)