1

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?

3
  • 1
    Uh, the first open obviously overwrites any previous contents. Commented Feb 26, 2022 at 10:44
  • 1
    You open the output file in 'w' mode. This will create a new file. You then open it with 'a' mode to append. What you probably want to do is to check if the file exists. If it exists don't open in 'w' mode and write the column heading just move on to append mode Commented Feb 26, 2022 at 10:45
  • That makes sense. The more I learn. Thanks both of you! Commented Feb 26, 2022 at 10:49

1 Answer 1

3

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]) 
Sign up to request clarification or add additional context in comments.

2 Comments

Additionally, you don't have to call order_csv.close() when using with ... as, as it's handled automatically.
That wasn't my code, and you're right - I knew it wasn't necessary. Thanks a ton!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.