By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,688 Members | 1,177 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,688 IT Pros & Developers. It's quick & easy.

reading a column from text

P: 1
Hi I have large text file as follows.

EXPERIMENT : KSAS1201 SG CLIMAT CHANGE STUDY ON KANSAS
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) 0.0262 -99

I wish to read only a certain column from this file such as just a column below simulation and measured
Jun 6 '12 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 391
Hi

We often like to see the code you've attempted so far, what results you've got and what you're looking for.

However, the simple way to do this is to use regular expressions.

For example:
Expand|Select|Wrap|Line Numbers
  1. import re
  2. myFile=open("input.txt")
  3.  
  4. result={}   # dictionary for results  
  5. p=re.compile(r'(.*) (.*) (.*)')
  6. start=False
  7. for line in myFile:
  8.     if not start: #continue until the data starts
  9.         if line[0]=="@":
  10.             start=True
  11.         continue
  12.     m=p.match(line)
  13.     result[m.group(1)] = [float(m.group(2)),float(m.group(3))]
  14.  
  15. for k in result:
  16.     print "##############"
  17.     print "key:",k
  18.     print "value:",result[k]
uses the fact that regular expressions are by default hungry, and therefore finds the last two spaces in the lines. This yields the following:
Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. ##############
  3. key: Unit wt at maturity (g [dm]/unit)
  4. value: [0.0262, -99.0]
  5. ##############
  6. key: Physiological maturity day (dap)
  7. value: [160.0, -99.0]
  8. ##############
  9. key: Yield at harvest maturity (kg [dm]/ha)
  10. value: [8478.0, -99.0]
  11. ##############
  12. key: Anthesis day (dap)
  13. value: [115.0, -99.0]
  14. ##############
  15. key: Number at maturity (no/m2)
  16. value: [32377.0, -99.0]
  17. ##############
  18. key: Panicle Initiation day (dap)
  19. value: [62.0, -99.0]
  20. >>> 
Jun 7 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.