Blog Archive

Saturday, November 4, 2017

python program to read and write matrix from/to a given file

python program to read a matrix from a given file - Stack Overflow:



https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html#numpy.loadtxt



#FILE NAME: readANDWrite.py

#!/usr/bin/python

#USING EXAMPLE:  python readANDWrite.py input.txt output.txt

import numpy as np

col0=np.loadtxt(sys.argv[1], dtype='str',usecols=0);  # READ

col1=np.loadtxt(sys.argv[1], dtype='f',usecols=1);



names=np.array(['NAME_1', 'NAME_2', 'NAME_3'])

floats  =np.array([ 0.1234 ,  0.5678 ,  0.9123 ])


ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])

ab['var1'] = names
ab['var2'] = floats
np.savetxt(sys.argv[2], ab, fmt="%10s %10.3f") #Write












'via Blog this'

No comments:

Post a Comment