[英]Python + CSV : How can I create a new csv and write new columns to that in Python?
I want to make a new CSV from scratch. 我想从头开始制作新的 CSV。 In that CSV I'll store new cells row wise.
在该CSV中,我将逐行存储新单元格。 Each cell value will be computed dynamically and row will be stored to the csv in a loop.
每个单元格值将动态计算,并且行将循环存储到csv中。 Unfortunately, all of the available codes for this purpose are for already existing CSVs.
不幸的是,用于此目的的所有可用代码均适用于现有的CSV。 A code without using Pandas dataframe will be preferred.
最好使用不使用Pandas数据框的代码。
you can create your own csv file, here I would like to show you how you can create csv file with headers. 您可以创建自己的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)
if you have data coming in as a list , 如果您将数据作为列表输入,
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)
This could help you! 这可以帮助您!
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.