简体   繁体   中英

iterating through a file Python

I am looking to tally up all of the Baseline numbers in the Isc, Voc Imp, Vmp, FF and Pmp columns individually and take the average for each column. Below is the file that I am reading in to my program (test_results.csv).

在此处输入图片说明

Here is my code.

from MyClasses import TestResult

def main():
        test = "test_results.csv"
        inputFile = open(test, 'r')
        user = TestResult()
        counter = 0.0
        hold = 0.0

        for i in range (4,10):
                for l in inputFile.readlines()[1:]:
                        split = l.split(",")
                        if user.getTestSeq(split[1]) == "Baseline":
                                num = float(user.getIsc(split[i]))
                                hold += num
                                counter += 1
                print counter
                print hold
                total = hold/counter
                print total

main()

I used the line

num = float(user.getIsc(split[i]))

with the hope that I could iterate through with the i, totaling one column, taking the average and moving to the next column. But I am not able to move to the next column. I just print out the same Isc column multiple times. Any ideas as to why? I am also looking to put the Test Sequences items in a list that I could iterate through in the same way for line

if user.getTestSeq(split[1]) == "Baseline":

so that I can tally up all the columns for Baseline, then move to tally up all columns for TC200, Hotspot and so on. Is this a good approach? wanted to solve the first iteration issue first before moving on to this one.

Thank you

You should use either DictReader from CSV Module or read_csv from pandas module

I recommend pandas module as you also perform operations on your data using.

import pandas as pd

df = pd.read_csv("test_results.csv")

df will contain your CSV table as is, no need to convert to floats or integers

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