Ale
Ale

Reputation: 87

Problems after using numpy.savetxt

i am programming with Python. this is my code:

def data_exp(nr, nc):
    data=numpy.zeros((nr, nc))
    print data
    for i in range(0, nr):
        for j in range (0, nc):
            data[i, j]=input('Insert values: ')
    numpy.savetxt(str(input('Insert the name of the file (ex: "a.txt"): ')), data)
    return data

the problem is that this program returns nothing! everything i put after the numpy.savetxt is ignored! can someone tell me how to overcome this problem?

Upvotes: 0

Views: 1538

Answers (1)

talonmies
talonmies

Reputation: 72350

Your problem is the inappropriate use of input. input is the equivalent of eval(raw_input()). The eval() call will try and evaluate the text you input as python source code in the context of globals and locals within your program, which is clearly not want you want to do in this case. I am surprised you are not getting a runtime error reporting that the string you enter is not defined.

Try using raw_input instead:

def data_exp(nr, nc):
    data=numpy.zeros((nr, nc))
    print data
    for i in range(0, nr):
        for j in range (0, nc):
            data[i, j]=input('Insert values: ')
    numpy.savetxt(str(raw_input('Insert the name of the file (ex: "a.txt"): ')), data)
    return data

EDIT:

Here is the code above, working for me in an ipython session. If you cannot get it to work, something else is wrong:

In [7]: data_exp(2,2)
[[ 0.  0.]
 [ 0.  0.]]
Insert values: 1
Insert values: 2
Insert values: 3
Insert values: 4
Insert the name of the file (ex: "a.txt"): a.txt
Out[7]: 
array([[ 1.,  2.],
       [ 3.,  4.]])

In [8]: data_exp??
Type:       function
Base Class: <type 'function'>
String Form:    <function data_exp at 0x2ad3070>
Namespace:  Interactive
File:       /Users/talonmies/data_exp.py
Definition: data_exp(nr, nc)
Source:
def data_exp(nr, nc):
    data=numpy.zeros((nr, nc))
    print data
    for i in range(0, nr):
        for j in range (0, nc):
            data[i, j]=input('Insert values: ')
    numpy.savetxt(str(raw_input('Insert the name of the file (ex: "a.txt"): ')), data)
    return data

In [9]: _ip.system("cat a.txt")
1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00

Upvotes: 2

Related Questions