1

I'm writing code to populate two columns from a CSV file (row[0] and row[1]) using a list comprehension (transaction_list and revenue_list, respectively) in Python 3.6.3.

If I run the code below, I can get the script to populate revenue_list properly, but transaction_list will return an empty list.

import os, csv
csvpath = os.path.join('budget_data_1.csv')

with open(csvpath) as f:
   readcsv = csv.reader(f, delimiter=',')

   next(readcsv)

   revenue_list = [int(row[1]) for row in readcsv]
   print(revenue_list)

   transaction_list = [row[0] for row in readcsv]
   print(transaction_list)

On the other hand, if I run the code below (which comments out revenue_list = [int(row[1]) for row in readcsv]), I can get transaction_list to return the correct list.

import os, csv
csvpath = os.path.join('budget_data_1.csv')

with open(csvpath) as f:
   readcsv = csv.reader(f, delimiter=',')

   next(readcsv)

   #revenue_list = [int(row[1]) for row in readcsv]
   #print(revenue_list)

   transaction_list = [row[0] for row in readcsv]
   print(transaction_list)

Question: Why does the script return transaction_list as an empty list when I attempt to populate transaction_list and revenue_list as written?

grantaguinaldo
  • 109
  • 1
  • 3
  • 12
  • 2
    Because `readcsv` is an iterator that will be consumed once you iterated over it once. – timgeb Nov 20 '17 at 06:52
  • `readcsv` is an iterator that is extinguished after the first iteration. – cs95 Nov 20 '17 at 06:52
  • 1
    After the first read, call `f.seek(0)` to reset the file pointer. – cs95 Nov 20 '17 at 06:53
  • Make a list containing both things in a tuple. You could then process it again to get two separate lists for each parameter. Assuming its not huge. – Paul Rooney Nov 20 '17 at 06:55

0 Answers0