Manuel Almeida
Manuel Almeida

Reputation: 183

Reading a specific row & columns of data in a text file

I am new to Python and I need to extract data from a text file (.txt). I have a text file below I need to get the data from the third column below the text. I need to put the text into a python list

Version 3.6    CE-QUAL-W2
Lagoa das Furnas - 1 Ramo
Default hydraulic coefficients
Default light absorption/extinction coeffients
      JDAY          DLT         ELWS         T2
       4.0          5.0          6.0        7.0
       3.0          4.0          5.0        6.0
       3.0          5.0          7.0        6.0

I have tried this but it doesn´t work, i get all the rows

a=np.genfromtxt('file.txt', skip_header=5)

Upvotes: 1

Views: 6313

Answers (2)

askewchan
askewchan

Reputation: 46530

If you have a file that looks like the one shown, then you can skip the header lines and grab just one column with np.genfromtxt like this:

np.genfromtxt('filename.txt', skip_header=5, usecols=2)

Note that I wrote usecols=2, which gets the third column (col 0 is the first column). You can get more than one column using a list: usecols=[0,2] which would grab the first and third.

In [105]: from StringIO import StringIO

In [106]: s = StringIO("""Version 3.6    CE-QUAL-W2
   .....: Lagoa das Furnas - 1 Ramo
   .....: Default hydraulic coefficients
   .....: Default light absorption/extinction coeffients
   .....:       JDAY          DLT         ELWS         T2
   .....:        4.0          5.0          6.0        7.0
   .....:        3.0          4.0          5.0        6.0
   .....:        3.0          5.0          7.0        6.0""")

In [107]: np.genfromtxt(s, skip_header=5, usecols=2)
Out[107]: array([ 6.,  5.,  7.])

Upvotes: 0

edi_allen
edi_allen

Reputation: 1872

#updated
L = []
for index, line in enumerate(open('data.txt')):
    if index <= 4: #skip first 5 lines
        continue
    else:
         L.append(line.split()[2]) #split on whitespace and append value from third columns to list.
print(L)
#[6.0, 5.0, 7.0]

Upvotes: 1

Related Questions