Python3 - Loop through CSV and add row to variable for next loop?

Discussion in 'App Development' started by OptionsOptionsOptions, Mar 23, 2020 at 11:58 PM.

  1. Python 3.8.2
    • Loop through CSV file and add row to variable for next loop?


    Code:
    with open('final-output.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        for row in readCSV:
    
            result = round(float(row[0]),1)
    

    How do I pass result to a variable for the next loop? It would then be over written for the following loop.

    Example:
    5
    10
    15
    10
    2
    4


    5+10
    10+15
    15+10
    10+2
    2+4

    Thanks
     
  2. gaussian

    gaussian

    You can use a variable outside the loop that you maintain.

    You can also use `with csv.reader(csvfile, delimiter=',') as readCSV` to do automatic resource clean up.

    If you are simply summing numbers there are easier ways such as `sum(numArray)` but this requires you to read all the numbers into an array beforehand.
     
  3. 2rosy

    2rosy

    you can shift and add. pandas, numpy, ... are the libraries you want. A for loop is what you don't want
    Code:
    import numpy as np
    a=[5,10,15,10,2,4]
    np.array(a[:-1]) + np.array(a[1:])