Home > other >  Append new line to CSV file
Append new line to CSV file

Time:02-26

I'm trying to append new data to a CSV file.

For example: I have 3 columns, namely, Quantity, Cost, Item.

And say, I have the following data:

  • Quantity = 20
  • Cost = 150
  • Item = Keyboard

Each time I use the code, it should create a new row for the data - the output would look like:

Quantity,Cost,Item
20,150,Keyboard
20,150,Keyboard

Instead, the following code only produces the following output each time I run it:

Quantity,Cost,Item
20,150,Keyboard

Code:

QUANTITY = 20
COST = 150
ITEM = "Keyboard"

with open('orders.csv', 'w', newline='') as order_csv:
    order_csv_write = csv.writer(order_csv)
    order_csv_write.writerow(
        ["QUANTITY", "COST", "ITEM"])

with open('orders.csv', 'a', newline='') as order_csv:
    order_csv_append = writer(order_csv)
    order_csv_append.writerow([QUANTITY, COST, ITEM])
    order_csv.close()

How do I go about it the right way?

CodePudding user response:

Each time you use the write w mode, it overwrites the file, deleting the old contents in the process.

It might make more sense to first check if the file exists, and write the header row only if it doesn't. Here's one way to do that, and it shows the behaviour required in your question:

import csv
from pathlib import Path


QUANTITY = 20
COST = 150
ITEM = "Keyboard"
FILE_PATH = Path('orders.csv')

if not FILE_PATH.exists():
    with open(FILE_PATH, 'w', newline='') as order_csv:
        order_csv_write = csv.writer(order_csv)
        order_csv_write.writerow(
            ["QUANTITY", "COST", "ITEM"])

with open(FILE_PATH, 'a', newline='') as order_csv:
    order_csv_append = csv.writer(order_csv)
    order_csv_append.writerow([QUANTITY, COST, ITEM])
  • Related