Python Index out of range on Cash flow
Question: Having trouble with a code that should read comma separated values out of .txt
file, sort into arrays based on negativity, and then plot data. Here is the
code, followed by 2 .txt files, the first one works, but the second one
doesn't

    
    
    #check python is working
    print "hello world"
    
    #import ability to plot and use matrices
    import matplotlib.pylab as plt
    import numpy as np
    
    #declare variables
    posdata=[]
    negdata=[]
    postime=[]
    negtime=[]
    interestrate=.025
    
    
    #open file
    f= open('/Users/zacharygastony/Desktop/CashFlow_2.txt','r')
    data = f.readlines()
    
    #split data into arrays
    for y in data:
        w= y.split(",")
        if float(w[1])>0:
            postime.append(int(w[0]))
            posdata.append(float(w[1]))
        else:
            negtime.append(int(w[0]))
            negdata.append(float(w[1]))
    
    print "Inflow Total: ", posdata
    print "Inflow Time: ", postime
    print "Outflow Total: ", negdata
    print "Outflow Time: ", negtime
    
    #plot the data
    N=len(postime)
    M=len(negtime)
    
    ind = np.arange(N+M)  # the x locations for the groups
    width = 0.35       # the width of the bars
    
    fig, ax = plt.subplots()
    rects1 = ax.bar(ind, posdata+negdata, width, color='r')
    
    # add some
    ax.set_ylabel('Cash Amount')
    ax.set_title('Cash Flow Diagram')
    ax.set_xlabel('Time')
    
    plt.plot(xrange(0,M+N))
    plt.show()'
    

.txt 1_**___ ____**

    
    
    0,3761.97
    1,-1000
    2,-1000
    3,-1000
    4,-1000
    

.txt 2_**___ _____ _**

    
    
    0,1000
    1,-1000
    2,1000
    3,-1000
    

My error is as follows:

    
    
    >>> runfile('/Users/zacharygastony/cashflow.py', wdir=r'/Users/zacharygastony')
    hello world
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/zacharygastony/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
    execfile(filename, namespace)
      File "/Users/zacharygastony/cashflow.py", line 24, in <module>
        if float(w[1])>0:
    IndexError: list index out of range
    


Answer: One error that I can spot is with " if float(w[1])>0:" -- it shoudl take into
account that the w[1] would be a set of two values separated by a space. Here
is how w would look like for the second file: "['0', '1000 1', '-1000 2',
'1000 3', '-1000\n']". So, w[1] would be "1000 1" and taking a float for this
value would be an error. So, if you really want to access the second element,
then one way is to split it using the default space delimiter and pick the
first one (or the second one). Something like: "if
float((w[1].split())[0])>0:".

