简体   繁体   中英

Unable to access the values from the .csv file using Python3?

Using the following Python3 code, I am able to access the first column values but unable to access subsequent columns. The error is:

IndexError: list index out of range

with open('smallSample.txt', 'r') as file:
    listOfLines = file.readlines()
    for line in listOfLines:
        print(line.strip())   
    header = listOfLines[0] #with all the labels
    print(header.strip().split(','))
    for row in listOfLines[1:]:
        values = row.strip().split(',')
        print(values[0]) #Able to access 1st row elements
        print(values[1]) #ERROR Unable to access the Second Column Values
        '''IndexError: list index out of range'''

The smallSample.txt data stored is:

Date,SP500,Dividend,Earnings,Consumer Price Index,Long Interest Rate,Real Price,Real Dividend,Real Earnings,PE10

1/1/2016,1918.6,43.55,86.5,236.92,2.09,2023.23,45.93,91.22,24.21

2/1/2016,1904.42,43.72,86.47,237.11,1.78,2006.62,46.06,91.11,24

3/1/2016,2021.95,43.88,86.44,238.13,1.89,2121.32,46.04,90.69,25.37```

Actually, your values is not a list. It is re-initialized again and again in for loop. Use this code:

with open('data.txt', 'r') as file:
    listOfLines = file.readlines()
    for line in listOfLines:
        print(line.strip())   
    header = listOfLines[0] #with all the labels
    print(header.strip().split(','))
    values = []   # <= look at here
    for row in listOfLines[1:]:
        values.append(row.strip().split(',')) # <= look at here
    print(values[0])  # <= outside for loop
    print(values[1])


with open('SP500.txt', 'r') as file:
    lines = file.readlines()
    #for line in lines:
        #print(line)
    #header = lines[0]
    #labels = header.strip().split(',')
    #print(labels)
    listOfData = []
    totalSP = 0.0
    for line in lines[6:18]:
        values = line.strip().split(',')
        #print(values[0], values[1], values[5])
        totalSP = totalSP + float(values[1])
        listOfData.append(float(values[5]))

    mean_SP = totalSP/12.0
    #print(listOfData)
    max_interest = listOfData[0]
    for i in listOfData:
        if i>max_interest:
            max_interest = i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM