簡體   English   中英

Python + CSV:如何在Python中創建一個新的csv並為此寫入新的列?

[英]Python + CSV : How can I create a new csv and write new columns to that in Python?

我想從頭開始制作新的 CSV。 在該CSV中,我將逐行存儲新單元格。 每個單元格值將動態計算,並且行將循環存儲到csv中。 不幸的是,用於此目的的所有可用代碼均適用於現有的CSV。 最好使用不使用Pandas數據框的代碼。

最終CSV應該如下所示: 在此處輸入圖片說明

您可以創建自己的csv文件,在這里我想向您展示如何創建帶標題的csv文件。

import csv
rowHeaders = ["Title", "Coupon code", "Description", "Image path", "Website link", "offer expire"]
fp = open('groupon_output.csv', 'w')
mycsv = csv.DictWriter(fp, fieldnames=rowHeaders)
#write header will write your desire header
mycsv.writeheader()

# you can write multiple value to take it inside the loop
#you can write row values using dict writer
title="testing"
coupon_code="xx"
description="nothing much"
image_path="not given"
current_page_url="www.google.com"

mycsv.writerow({"Title": title, "Coupon code": coupon_code, "Description": description,"Image path": image_path, "Website link": current_page_url,"offer expire": "Not Avialable"})

import csv

data =  [
        [ 'a','b','c','d'],
        [ 'b','1','2','3'],
        [ 'c','4','5','6'],
        [ 'd','7','8','9'],
        ]

with open ('output.csv', 'w') as output:
    writer = csv.writer(output)
    writer.writerows(data)

如果您將數據作為列表輸入,

import csv

list_1 = ['UOM','BelRd(D2)','Ulsoor(D2)','Chrch(D2)','BlrClub(D2)','Indrangr(D1)','Krmngl(D1','KrmnglBkry(D1)']
list_2 = ['PKT',0,0,0,0,0,0,1]

with open('/path/filename.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    writer.writerow(list_1)
    writer.writerow(list_2)

這可以幫助您!

def header():
    # Instead of hard coding like below, pass variables which hold dynamic values
    # This kind of hard coding can you help you when headers are fixed
    h1 = ['Date']  
    h2 = ['Feed']
    h3 = ['Status']
    h4 = ['Path']

    rows = zip(h1, h2, h3, h4)

    with open('test.txt', 'a') as f:
        wr = csv.writer(f)
        for row in rows:
            wr.writerow(row)
        f.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM