Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将列表列表写入txt文件?_Python - Fatal编程技术网

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

Python 如何将列表列表写入txt文件?,python,Python,我有一个16个元素的列表,每个元素又有500个元素。我想把它写入一个txt文件,这样我就不必再从模拟中创建列表了。如何执行此操作,然后再次访问列表?要存储列表: import cPickle savefilePath = 'path/to/file' with open(savefilePath, 'w') as savefile: cPickle.dump(myBigList, savefile) 要取回它: import cPickle savefilePath = 'path/t

我有一个16个元素的列表,每个元素又有500个元素。我想把它写入一个txt文件,这样我就不必再从模拟中创建列表了。如何执行此操作,然后再次访问列表?

要存储列表:

import cPickle

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

import cPickle

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

看看pickle对象序列化。使用pickle,您可以序列化列表,然后将其保存到文本文件中。稍后,您可以从文本文件中“取消勾选”数据。数据将被取消勾选到列表中,您可以在python中再次使用它@我想先找到答案,看看

虽然
pickle
无疑是一个不错的选择,但对于这个特定的问题,我更愿意使用
numpy
将其保存到一个csv文件或一个包含16列的普通txt文件中

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)

在这种情况下,我确实建议使用cPickle,但您应该采取一些“额外”步骤:

  • ZLIB输出
  • 对其进行编码或加密
这样做有以下优点:

  • ZLIB将缩小其大小
  • 加密可以防止酸洗劫持

是的,泡菜不安全!请参见Pickle可以工作,但缺点是它是一种特定于Python的二进制格式。另存为JSON,便于阅读和在其他应用程序中重复使用:

import json

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

with open('Jfile.txt','w') as myfile:
    json.dump(LoL,myfile)
该文件现在包含:

[[0, 1, 2, 3, 4], ["A", "B", "C", "D", "E"], [0, 1, 2, 3, 4]]
要稍后将其取回,请执行以下操作:

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

print newList

你看过pickle吗?到目前为止你试过什么?不确定您是否关心列表是否位于文本文件中,或者是否关心是否能够访问以前生成的列表而无需每次重新生成。查看cpickle并找到了一种很好的方法。谢谢。如果您想要纯txt文件,请查看下面我的答案。JSON是保存数据结构的另一个选项,它的优点是可以被其他设备(如人类)读取。