如何在Python中追加新列到CSV?

2024-03-28 10:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

[输入]

listBox = ['status: 123', 'company: test']

[期望输出]

'zzzz' - column A already exists
'status: 123' - should be written in column B in a single cell.  
'company: test' - should be written in column C in a single cell.

我试过:

编辑1

def writeToCSV():
    checkpointList = ['CompanyID: test', 'StatusCode: 123']
    data = [str(checkpointList).split(",")]
    path = "output.csv"
    with open(path, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)
writeToCSV()

但这将覆盖现有列


Tags: csvintestdatastatuscellcolumnbe
1条回答
网友
1楼 · 发布于 2024-03-28 10:23:41

在下面尝试-writerow需要单个list。你知道吗

import csv
def writeToCSV():
    checkpointList = ['CompanyID: test', 'StatusCode: 123']
    path = r"C:\out.txt"
    with open(path, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        writer.writerow(checkpointList)
writeToCSV()

上面写着-

CompanyID: test,StatusCode: 123

相关问题 更多 >