简体   繁体   English

将Python数组写入txt文件,每行一个数组

[英]Writing Python arrays into txt file, one array per line

I would like to write a number of Python Arrays into a txt file, with one array per line. 我想将多个Python数组写入txt文件,每行一个数组。 After which I would like to read the Arrays line by line. 之后,我想逐行阅读Arrays。

My work in progress code below. 我的工作代码如下。 The problem I am working on involves about 100,000 arrays (length of L) 我正在研究的问题涉及大约100,000个数组(L的长度)

from __future__ import division
from array import array

M = array('I',[1,2,3])
N = array('I',[10,20,30])

L = [M,N]

with open('manyArrays.txt','w') as file:
    for a in L:
        sA = a.tostring()
        file.write(sA + '\n')

with open('manyArrays.txt','r') as file:
    for line in file:   
        lineRead = array('I', [])
        lineRead.fromstring(line)
        print MRead

The error message I get is 我收到的错误消息是

lineRead.fromstring(line)
ValueError: string length not a multiple of item size

You can either use numpy function for this, or code lines yourself: 您可以为此使用numpy函数,也可以自己编写代码行:

You could concatenate your arrays in one 2D array and save it directly with np.savetxt, load it with np.genfromtext : 您可以将一个数组连接到一个2D数组中,然后直接将其保存到np.savetxt中,并使用np.genfromtext加载它:

M = np.array([1,2,3],dtype='I')
N = np.array([10,20,30],dtype='I')
data= np.array([M,N])

file='test.txt'
np.savetxt(file,data)
M2,N2 = np.genfromtxt(file)

Or do : 或做:

file2='test2.txt'
form="%i %i %i \n"
with open(file2,'w') as f:
    for i in range(len(data)):
        f.write(form % (data[i,0],data[i,1],data[i,2]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM