简体   繁体   English

Append 新行到 CSV 文件

[英]Append new line to CSV file

I'm trying to append new data to a CSV file.我正在尝试将 append 新数据写入 CSV 文件。

For example: I have 3 columns, namely, Quantity , Cost , Item .例如:我有 3 列,即QuantityCostItem

And say, I have the following data:并说,我有以下数据:

  • Quantity = 20数量 = 20
  • Cost = 150成本 = 150
  • Item = Keyboard项目 = 键盘

Each time I use the code, it should create a new row for the data - the output would look like:每次我使用代码时,它都应该为数据创建一个新行——output 看起来像:

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

Instead, the following code only produces the following output each time I run it:相反,以下代码每次运行时只产生以下 output:

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?请问我go怎么用正确的方法呢?

Each time you use the write w mode, it overwrites the file, deleting the old contents in the process.每次使用 write w模式时,它都会覆盖文件,删除过程中的旧内容。

It might make more sense to first check if the file exists, and write the header row only if it doesn't.首先检查文件是否存在可能更有意义,只有在不存在时才写入 header 行。 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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