python calculate table without (numpy)
Question: Hi i have a quick question about finding line # from my text and use this
line# to calculate something

(this is not hw question and i just start learning about python)

ex~ if my text looks like

    
    
     100 200 300
     400 500 600 
     700 800 900
     120 130 140
     150 160 170
    

and

    
    
    f1 = open('sample4.txt','r')
    
    line_num = 0
    search_phrase = "100"
    
    for line in f1.readlines():
    line_num += 1
    if line.find(search_phrase) >= 0:
        x = line_num
        print (x)
    
    import numpy
    data = numpy.loadtxt('sample4.txt')
    print(data[x:x+3,1].sum())
    

i could get

    
    
    1430.0 which is (200+500+800+130)
    

however, if my text looks like:

    
    
    apple is good
    i dont like apple
    100 200 300 
    400 500 600 
    700 800 900
    120 130 140 
    150 160 170
    i love orange
    

error pops up and said

    
    
     Traceback (most recent call last):
     File "C:/Python33/sample4.py", line 13, in <module>
     data = numpy.loadtxt('sample4.txt')
     File "C:\Python33\lib\site-packages\numpy\lib\npyio.py", line 827, in loadtxt
     items = [conv(val) for (conv, val) in zip(converters, vals)]
     File "C:\Python33\lib\site-packages\numpy\lib\npyio.py", line 827, in <listcomp>
     items = [conv(val) for (conv, val) in zip(converters, vals)]
     ValueError: could not convert string to float: b'apple'
    

i think the reason why this error pops up becasue **NUMPY**

is there any way to make this correct?? without using some skip_header or
skip_footer


Answer: It seems that loadtxt can use a file handle as input, so one (maybe ugly)
trick might be to first determine the line of your interesting text as you
did, then reopen the file, read the first few uninteresting lines and then
pass the file handle to loadtxt (untested):

    
    
    fname = 'sample4.txt'
    search_phrase = '100'
    
    with open(fname) as fid:
        for linenum, line in enumerate(fid):
            if search_phrase in line:
                break #if the n-th line is interesting, line_num = n-1
    
    #reopen file
    with open(fname) as fid:
        for i in xrange(linenum):
            fid.readline() #throw away uninteresting lines
        data = np.loadtxt(fid) #pass file handle
    
    print(data[:3,1].sum()) #interesting stuff is now in first row
    

But what is wrong with using skiprows? The second part could then be changed
into

    
    
    #get linenum as before
    data = np.loadtxt(fname, skiprows = linenum)
    print(data[:3,1].sum()) #interesting stuff is now in first row
    

