How do you index a list in a txt file and call on the indexed values?

1.4k views Asked by At

I am attempting to index my list, and then call on the last two values in each list separately.
For example

['Ashe', '1853282.679', '1673876.66', '1 ', '2 \n']
['Alleghany', '1963178.059', '1695301.229', '0 ', '1 \n']
['Surry', '2092564.258', '1666785.835', '5 ', '6 \n']`    

I want my code to return (1, 2) #from the first list (0, 1) #from the second list (5, 6) #from the third list

my code so far includes:

def calculateZscore(inFileName, outFileName):
    inputFile = open(inFileName, "r")
    txtfile = open(outFileName, 'w')

    for line in inputFile:
        newList = (line.split(','))

    print newList

    inputFile.close()
    txtfile.close()


if __name__ == "__main__":
    main()    

(I have been making attempts at indexing but the fact that there is a string in my list has been making it difficult)

2

There are 2 answers

4
2ps On BEST ANSWER

First, don’t put quotes around your program code. Second, here are some quick pointers:

def calculateZscore(inFileName, outFileName):
    # use with to open files to avoid having to `close` files
    # explicitly
    # inputFile = open(inFileName,"r")  
    # txtfile = open(outFileName, 'w')

    with open(inFileName, 'r') as inputFile, open(outFileName, 'w') as txtFile:
        for line in inputFile:
            newList = line.strip().split(',')
            last_two = newList[-2:] # this gets the last two items in the list  
            print last_two 



# indentation matters in python, make sure this line is indented all the way to the left, otherwise python will think it is part of 
# a different function and not the main block of running code
if __name__ == "__main__":
    main()

As an aside, it looks like you are reading CSV file. python has built-in CSV processing that you may want to consider:

def calculateZscore(inFileName, outFileName):
    import csv
    with open(inFileName, 'r') as inputFile, open(outFileName, 'w') as txtFile:
        reader = csv.reader(inputFile)
        for newList in reader:
            last_two = newList[-2:] # this gets the last two items in the list  
            print last_two 
0
fedepad On

Use

newList = line.rstrip('\n').split(',')[-2:]

but this line should be intended with respect to the for loop, not as you show in your code example.