Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument 1 must be an iterator - what am I doing wrong?

I've got a section of code in a project that's supposed to be reading a CSV file and writing each row to an XLSX file. Right now I'm getting the error "argument 1 must be an iterator" when I run via command line.

Here is the relevant code:

import os
import openpyxl
import csv
from datetime import datetime
from openpyxl.reader.excel import load_workbook

...

plannum = 4

...

alldata_sheetname = ("All Test Data " + str(plannum))
wb = load_workbook("testingtemplate.xlsx", keep_vba=True)

...

ws_testdata = wb.get_sheet_by_name(alldata_sheetname)

...

with open("testdata.csv", 'r') as csvfile:
    table = csv.reader(csvfile)
    for row in table:
        ws_testdata.append(row)

csv_read = csv.reader(csvfile)

...

And the specific error reads: "TypeError: argument 1 must be an iterator", and is referencing the last line of code I've provided.

Since it didn't complain about the first time I used csvfile, would it be better if I did something like csvfile = open("testdata.csv", "r") instead of using the with (and is that what I'm doing wrong here)? If that's the case, is there anything else I need to change?

Thanks to anyone who helps!!

like image 855
DJGrandpaJ Avatar asked Feb 11 '16 21:02

DJGrandpaJ


1 Answers

You've closed the file by the time you get to csv_read = csv.reader(csvfile). Alternately you can keep the file open and store what you need in variables so you don't have to iterate over the file twice. E.g.:

csvfile = open("testdata.csv", "r")
table = csv.reader(csvfile)
for row in table:
    ws_testdata.append(row)
    # store what you need in variables
csvfile.close()
like image 150
mechanical_meat Avatar answered Nov 17 '22 13:11

mechanical_meat