4

I have a text file as following:

1.25        177.        
1.50        220.        
2.00        272.        
5.00        427.    
10.00       556.        
25.00       763.        
50.00       916.        

and i want to read second last value from second column. I can move onto line of interest but somehow can't figure out a way to read required value. Any help would be appreciative.

a = open("test.txt","r")
b = a.readlines()
a.close()

count = 0
for line in b:
    count += 1
    if count > 6:
        print line,
4
  • 5
    Does this question belong on GIS.SE? How is this GIS related?
    – Fezter
    Jan 21, 2013 at 11:17
  • What are the corner cases for your example? Will there always be a trailing .? Will the second column always be 3 digits long?
    – blah238
    Jan 21, 2013 at 11:29
  • This really should be a Stack Overflow question. Jan 21, 2013 at 15:21
  • @Fetzer et al. I agree on it. Text file results are used as string in conjunction with shapefile attributes which led me to post it here. But the question only as it is posted here should be on Stack Overflow.
    – Ibe
    Jan 21, 2013 at 19:20

2 Answers 2

3

There are a couple of ways to do this. The quickest would be to read the file as you have done and then use the string split function.

b = open("test.txt", "r").readlines()
line = b[-2].split() #Gets the second last value from the list and split on whitespace
return float(line[-1])

However this isn't very reusable. If you're doing this for lots of similar files I'd look at the csv module for working with delimited text.

0
file = open("input.txt", 'r')
lines = file.readlines()
file.close()



for line in lines:
    parts = line.split() # split line into parts
    if len(parts) > 1:
        column2 = parts[1]
        columnLength = len(column2)
        desireValue = column2[columnLength-3]
        print desireValue

for given text file in the question, this code will print 7
2
7
2
5
6
1

1
  • What is the reason behind the down vote ??!!
    – Emi
    Jan 22, 2013 at 15:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.