参数1必须是迭代器-我做错了什么? [英] Argument 1 must be an iterator - what am I doing wrong?

查看:378
本文介绍了参数1必须是迭代器-我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中有一段代码应该读取CSV文件并将每一行写入XLSX文件.现在,通过命令行运行时,出现错误参数1必须是迭代器".

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.

以下是相关代码:

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)

...

特定错误显示为:"TypeError:参数1必须是迭代器",并且引用了我提供的最后一行代码.

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

因为它没有抱怨我第一次使用csvfile,所以如果我做类似csvfile = open("testdata.csv", "r")的事情而不是使用with会更好(这就是我在这里做错了) ?如果是这样,我还需要更改吗?

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!!

推荐答案

csv_read = csv.reader(csvfile)时,您已经关闭了文件.或者,您可以保持文件打开并将所需的内容存储在变量中,这样就不必遍历文件两次.例如:

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()

这篇关于参数1必须是迭代器-我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆