简体   繁体   中英

How to Add A New Row Into an Existing CSV file with CSV.Writer?

I am trying to implement a method that adds a new row into an existing csv file that I am using for as my "database"

I have the following code so far (a class and some methods left out for simplification):

My Csv File looks like this:

CSV File

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

    def make_dict_items(self):
        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 show_available(self):
        for item in self.result:
           print(item)

     def add_item(self):

How would I implement in add_item adding an item to the csv file, that is then added to the list of dicts, and shown when I return all the items in show_available() ?

I think I have a start, I tried something along the lines of:

def add_item(self):
       item_num = input("What is the items #?\n")
       price = input("What is the items price?\n")
       quant = input("What is the items quantity?\n")
       name = input("What is the items name?\n")
       with open("Items2.csv") as  fp:
           writer = csv.writer(fp)
           labels = next(reader, None)
       

but wasnt really sure how to make the inputs from the user into each specific row to insert? For example, the item # input should go into a new row, etc. How would this be done?

Turn the input into a dictionary, and add it to the self.result list. Then append the row data to the file.

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

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