user1443274
user1443274

Reputation: 11

reading a column from text using python

EXPERIMENT : KSAS1201 SG CLIMAT CHANGE
DATA PATH : C:\DSSAT45\Sorghum\
TREATMENT 1 : N.American SGCER045

@     VARIABLE                              SIMULATED     MEASURED
  --------                                 -------     --------
  Panicle Initiation day (dap)                   62          -99
  Anthesis day (dap)                            115          -99
  Physiological maturity day (dap)              160          -99
  Yield at harvest maturity (kg [dm]/ha)       8478          -99
  Number at maturity (no/m2)                  32377          -99
  Unit wt at maturity (g [dm]/unit)           .0262          -99  

Hi i have text file like above. I wish to know how to read only column ( like whole colum below simulated and Measured one by one) if possible i also like to know how to import these column in Excel file using python.

Upvotes: 0

Views: 373

Answers (3)

Jon Clements
Jon Clements

Reputation: 142206

from itertools import islice

with open('some.file') as fin:
    for line in islice(fin, 6, None):
        desc, simulated, measured = ' '.join(line.split()).rsplit(' ', 2)
        # do any necessary conversions

Then look at xlwt/csv or XML or whatever so it can be read back into something else...

Upvotes: 0

thebjorn
thebjorn

Reputation: 27321

Theodros has given a good answer for reading the file. To get it into excel, you can either save it as csv (using the csv module), or you can try the xlwt module (available from PyPi).

Upvotes: 0

tzelleke
tzelleke

Reputation: 15345

Simple way to read the columns into lists (assuming that the header is always 6 lines):

simulated = []
measured = []

with open('input.file') as f:
    for l in f.readlines()[6:]:
        l = l.split()
        simulated.append(l[-2])
        measured.append(l[-1])

print simulated
print measured

gives:

['62', '115', '160', '8478', '32377', '.0262']
['-99', '-99', '-99', '-99', '-99', '-99']

Note that the lists still contain the string representation of the numbers. Parse to numbers with:

simulated.append(float(l[-2]))
measured.append(int(l[-1]))

Upvotes: 1

Related Questions