2

I am trying to read specific columns from a CSV file. Everything is running fine but apparently the for loop is not working. i.e. when I am trying to print "in else" inside for loop, I am getting nothing.

with open(path) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    row_count = sum(1 for line in csv_file)
    print(row_count)
    companyName = [None]*row_count
    reportID = [None]*row_count
    date = [None]*row_count
    line_count = 1
    print(line_count)
    for row in csv_reader:
        print('in else')
        companyName[line_count-1] = row[1]
        print(row[1])
        reportID[line_count-1] = row[2]
        date[line_count-1] = row[4]
        line_count += 1
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    `row_count = sum(1 for line in csv_file)` you've exhausted your iterator – juanpa.arrivillaga Dec 14 '18 at 11:01
  • 2
    Related: https://stackoverflow.com/questions/10522769/why-can-i-read-lines-from-file-only-one-time – TrebledJ Dec 14 '18 at 11:02
  • 1
    delete `row_count = sum(1 for line in csv_file)` - replace `companyName = [None]*row_count` with `companyName = []` - same for `reportID, date`. Use `companyName.append(row[1])` - similarly for `reportID, date` – Patrick Artner Dec 14 '18 at 11:05

0 Answers0