I want to make a new CSV from scratch. In that CSV I'll store new cells row wise. Each cell value will be computed dynamically and row will be stored to the csv in a loop. Unfortunately, all of the available codes for this purpose are for already existing CSVs. A code without using Pandas dataframe will be preferred.
4 Answers
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)
2 Comments
Debbie
Each cell value will be computed dynamically and row will be stored to the csv in a loop. Can u modify your code for that?
Shijith
@Debbie, you can append each cell value for a row to a list and write to a csv file. change will be
with open('/path/filename.csv', 'a', newline='') as outfile:, which will append lines to the end of fileyou can create your own csv file, here I would like to show you how you can create csv file with headers.
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"})
Comments
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()
