Reading rows from a CSV file in Python

前端 未结 10 2380
慢半拍i
慢半拍i 2020-11-30 23:58

I have a CSV file, here is a sample of what it looks like:

Year:  Dec: Jan:
1      50   60
2      25   50
3      30   30
4      40   20
5      10   10
         


        
10条回答
  •  一整个雨季
    2020-12-01 00:50

    #  This program reads columns in a csv file
    import csv
    ifile = open('years.csv', "r")
    reader = csv.reader(ifile)
    
    # initialization and declaration of variables
    rownum = 0
    year = 0
    dec = 0
    jan = 0
    total_years = 0`
    
    for row in reader:
        if rownum == 0:
            header = row  #work with header row if you like
        else:
        colnum = 0
        for col in row:
            if colnum == 0:
                year = float(col)
            if colnum == 1:
                dec = float(col)
            if colnum == 2:
                jan = float(col)
            colnum += 1
        # end of if structure
    
    # now we can process results
    if rownum != 0:
        print(year, dec, jan)
        total_years = total_years + year
        print(total_years)
    
    # time to go after the next row/bar
    rownum += 1
    
    ifile.close()
    

    A bit late but nonetheless... You need to create and identify the csv file named "years.csv":

    Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10

提交回复
热议问题