I have a csv file [without header]:
1,0,1,a
2,1,2,b
3,4,5,c
How do I convert it to a format with today's date and file-2 to each row?
1,0,1,a,2021-07-22,file2
2,1,2,b,2021-07-22,file2
3,4,5,c,2021-07-22,file2
Is this possible to do? When I tried using csvwriter, I could append only to end.
with open("temp_csv.csv","a") as fout:
writer = csv.writer(','+date+',file2\n')
print(writer)
If you need to use the CSV module, then this works.
Your problem is you were trying to manipulate the csv inplace. Instead, you should read each line, process the line, and then write it to a new output csv file.
import csv
from datetime import datetime
todays_date = datetime.today().strftime('%Y-%m-%d')
with open("in.csv","r") as fin, open("out.csv", 'w', newline='') as fout:
reader = csv.reader(fin)
writer = csv.writer(fout)
for line in reader:
line.append(todays_date)
line.append("file2")
writer.writerow(line)