Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append new line to CSV file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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?

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading