Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm trying to read some data from a csv file. The problem is that the list is only displayed when print(a) is under the "if" block otherwise , it only displays the last item in the list

 def products_per_command():

    a=[]

    with open('commande_client.csv') as csv_file:

        Numero_commande=input ('entrez le numero de la commande que vous cherchez :' )

        csv_reader = csv.reader(csv_file, delimiter=';')

        for row in csv_reader:

            for i in row:

                if (i==Numero_commande):

                     a=[row[2],row[4]]

                     print(a)

the output here is:

 entrez le numero de la commande que vous cherchez :1

['af23', '150']

['ab12', '500']

['ab12', '214']

['af12', '21']

['ab12', '526']

['ab12', '223'] 

that's what i actually want but when i put the "print(a)" at the end of my function (not under any loop or "if") it only displays last item :

['ab12', '223']

1 Answer

0 votes
by (25.1k points)

The problem is that you have to use a.append([row[2],row[4]]) instead of using a=[row[2],row[4]]because you are trying to add items to a list.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...