Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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,
share|improve this question

closed as off topic by blah238, PolyGeo, artwork21, Nathan W, RyanDalton Jan 21 '13 at 15:20

Questions on Geographic Information Systems Stack Exchange are expected to relate to geographic information systems within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

5  
Does this question belong on GIS.SE? How is this GIS related? –  Fezter Jan 21 '13 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 '13 at 11:29
    
This really should be a Stack Overflow question. –  RyanDalton Jan 21 '13 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 '13 at 19:20
add comment

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
add comment
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

share|improve this answer
    
What is the reason behind the down vote ??!! –  Emi Jan 22 '13 at 15:30
add comment

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