简体   繁体   中英

TypeError: '_csv.writer' object is not an iterator

I am trying to implement a method in which I can add an item through user input to a row in a csv file.

My file looks like this enter image description here

With help from a previous question, I was able to implement a solution, but am now getting an erorr.

Here is the code:

class CsvReader:
    def __init__(self): 
        self.result = []

    def make_dict_items(self):
        #fn = os.path.join('subdir', "Items2.csv")
        with open("Items2.csv") as fp:
            reader = csv.reader(fp)
            labels = next(reader, None)
            result = []
            for row in reader:
                row[0] = int(row[0])
                row[1] = float(row[1])
                row[2] = int(row[2])
                pairs = zip(labels, row)
                self.result.append(dict(pairs))

    def add_item(self):
       item_num = int(input("What is the items #?\n"))
       price = float(input("What is the items price?\n"))
       quant = int(input("What is the items quantity?\n"))
       name = input("What is the items name?\n")
       new_row = [item_num, price, quant, name]
       with open("Items2.csv", "a+") as  fp:
           reader = csv.writer(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())

I am currently getting an error that TypeError: '_csv.writer' object is not an iterator. After researching, I understand this is basically because you cannot and should iterate over the list itself, not the writer. How would I do this?

Solved this due to the comments above I believe:

def add_item(self):
       item_num = int(input("What is the items #?\n"))
       price = float(input("What is the items price?\n"))
       quant = int(input("What is the items quantity?\n"))
       name = input("What is the items name?\n")
       new_row = [item_num, price, quant, name]
       with open("Items2.csv", "a+") as  fp:
           reader = csv.reader(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())

Made a simple mistake and didnt realize reader = csv.writer(fp) should be corrected to csv.reader(fp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM