numpy.loadtxt for one and more input lines

numpy, python, python-2.7

Solution

Try:

data1=numpy.loadtxt ( 'file1', unpack=True, ndmin = 1)

Problem

I have a datafile, which might be one or more rows. I read it using `numpy.loadtxt`. This has the feature that it makes my single row data a scalar. This is problematic, because I want to use a loop after read in. See the below example ``` $ cat file1 1 $ cat file2 1 2 $ python --version Python 2.7.6 $ python $ python temp.py 1.0 2.0 Traceback (most recent call last): File "temp.py", line 9, in <module> for x in data1: TypeError: iteration over a 0-d array ``` Code ``` import numpy data1=numpy.loadtxt ( 'file1', unpack=True ) data2=numpy.loadtxt ( 'file2', unpack=True ) for x in data2: print x for x in data1: print x ``` I also tried the solution of the related question: numpy loadtxt single line/row as list But I don't get it to work I added ``` data1 = data1 if usi.shape else [data1] ``` However, ``` $ python temp.py Traceback (most recent call last): File "temp.py", line 7, in <module> data1 = data1 if usi.shape else [data1] NameError: name 'usi' is not defined ``` I also tried `import usi`, but this is not installed on my system, and it seems a bit overdone for such a simple task. What am I doing wrong? I feel the solution is simple, but I couldn't find hints at http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

Original source

Related problems