Print content and multiple attributes of numpy array to text file
I have an array. My task is to print the array along with its shape, size, element size, dimensions and data type name. The output must be a text file - each attribute must be on a new line.
When I try to use the following code, I get an error:
File "<ipython-input-76-f4d4f45285be>", line 1, in <module>
print(a.shape)
AttributeError: 'NoneType' object has no attribute 'shape'
I tried two options, open a text file and np.savetxt
. Nothing works.
Here is the code:
import numpy as np
a = np.arange(15).reshape(3,5)
a = print(a)
shape = print(a.shape)
size = print(a.size)
itemsize = print(a.itemsize)
ndim = print(a.ndim)
dtype = print(type(a.dtype))
with open("demo_numpy.tx","w") as text:
text.write(a,shape,size,itemsize,ndim,dtype, file = text)
np.savetxt('demo_numpy.txt',[a,shape,size,itemsize,ndim,dtype])
What am I doing wrong and how can I correct my conclusion?
source to share
print
just prints the value passed to stdout
and returns None
. If you want to access a property, just do it without print
:
import numpy as np a = np.arange(15).reshape(3,5) shape = a.shape size = a.size itemsize = a.itemsize ndim = a.ndim dtype = a.dtype
And if you want to print
not assign the return value print
:
print(a)
print(a.shape)
print(a.size)
print(a.itemsize)
print(a.ndim)
print(a.dtype)
Note that you are writing the files incorrectly, in the first case you can only write one argument at a time, you either need str.join
them or do multiple text.write
s. In the second case, you should check the documentation numpy.savetxt
- it expects the array to be the second argument, not a list of multiple attributes.
For example:
with open("demo_numpy.tx","w") as text:
text.write(str(a))
text.write(str(shape))
text.write(str(size))
text.write(str(itemsize))
text.write(str(ndim))
text.write(str(dtype))
# or:
# text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])))
np.savetxt('demo_numpy.txt', a)
source to share
I would like to use something like this:
# import numpy as np
# my_array = np.arange(3)
metadata = [(method, getattr(my_array, method)) for method in dir(my_array) if (not callable(getattr(my_array, method))) and (not method.startswith('__'))]
names, values = zip(*metadata) # 2 lists
Then we go through names
and values
and write to a file.
source to share