简体   繁体   中英

Python method is not returning all the rows of csv file

I have a csv file in below format:

TestCase,Flag

test1,Y

test2,Y

test3,Y

test4,Y

TestCase and Flag are the column names.

Now in order to read all the rows of above csv file,i have written below code:

import csv
import os

csv.register_dialect(
    'usercredentials',
    delimiter=',',
    quotechar='"',
    doublequote=True,
    skipinitialspace=True,
    lineterminator='\r\n',
    quoting=csv.QUOTE_MINIMAL
)

    def testexecution():


        with open('location of above csv file', 'r+') as file:
            data = csv.DictReader(file, dialect='usercredentials')
            for row in data:
                testcase = row['TestCase']
                flag = row['Flag']
            return testcase, flag

But this method returns only the last row of the csv file,whereas i want this method to return all the rows.

Please suggest.

You are reassigning the variables you want to return. Simply add a list:

    with open('location of above csv file', 'r+') as file:
        data = csv.DictReader(file, dialect='usercredentials')
        testcase = []
        flag = []
        for row in data:
            testcase.append(row['TestCase'])
            flag.append(row['Flag'])
        return testcase, flag

In the for loop, you are replacing the value of the testcase and flag variables in each iteration and finally you are returning values from the last row. You probably want to use a dict or a list in which to append those values in each iteration and finally return those.

@Navidad20 suggests using lists, but this does not keep the testcase and flag values together, which will almost certainly mean that later you have to zip the two lists together. So I'd suggest instead:

with open('location of above csv file', 'r+') as file:
    data = csv.DictReader(file, dialect='usercredentials')
    result = []
    for row in data:
        result.append((row['TestCase'], row['Flag']))
    return result

That way you get a list of two-element tuples back, allowing you to write code like

for testcase, flag in testexcution():
    ...

to process the pairs in some other context.

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