I have this .csv file ...
id,first_name,last_name,email,date,opt-in
1,Jimmy,Reyes,[email protected],12/29/2016,FALSE
2,Doris,Wood,[email protected],04/22/2016,
3,Steven,Miller,[email protected],07/31/2016,FALSE
4,Earl,Parker,[email protected],01-08-17,FALSE
5,Barbara,Cruz,[email protected],12/30/2016,FALSE
I want to read the above shown csv file, transform data, and finally write the data in another text file, which should look like this ....
1,<tab>"first_name"="Jimmy","last_name"="Reyes","email"="[email protected]","date"="12/29/2016","opt-in"="FALSE"
2,<tab>"first_name"="Doris","last_name"="Wood","email"="[email protected]","date"="04/22/2016,,"opt-in"="0"
Also, If the opt-in value is empty, its should print "0".
Here is my code so far ....
import csv
import time
# Do the reading
with open('my-scripts/mock.csv', 'r') as f1:
#next(f1, None) # skip the headers
reader = csv.reader(f1)
new_rows_list = []
for row in reader:
if row[5] == '':
new_row = [row[0],'\t',row[1], row[2], row[3], row[4], '0']
new_rows_list.append(new_row)
else:
new_row = [row[0],'\t',row[1], row[2], row[3], row[4], row[5]]
new_rows_list.append(new_row)
f1.close() # <---IMPORTANT
# Do the writing
newfilename = 'my-scripts/ftp_745198_'+str(int(time.time()))
with open(newfilename, 'w', newline='') as f2:
writer = csv.writer(f2, quoting=csv.QUOTE_NONNUMERIC)
writer.writerows(new_rows_list)
f2.close()
The above code is generating this output, which is not what I exactly want ... I am unable to figure out how to print column names in each row as shown above in the desired output ...!
"id"," ","first_name","last_name","email","date","opt-in"
"1"," ","Jimmy","Reyes","[email protected]","12/29/2016","FALSE"
"2"," ","Doris","Wood","[email protected]","04/22/2016","0"
"3"," ","Steven","Miller","[email protected]","07/31/2016","FALSE"
"4"," ","Earl","Parker","[email protected]","01-08-17","FALSE"
"5"," ","Barbara","Cruz","[email protected]","12/30/2016","FALSE"
New CSV
id,first_name,last_name,email,date,opt-in,unique_code
1,Jimmy,Reyes,[email protected],12/29/2016,FALSE,ER45DH
2,Doris,Wood,[email protected],04/22/2016,,MU34T3
3,Steven,Miller,[email protected],07/31/2016,FALSE,G34FGH
4,Earl,Parker,[email protected],01-08-17,FALSE,ASY67J
5,Barbara,Cruz,[email protected],12/30/2016,FALSE,NHG67P
New expected output
ER45DH<tab>"id"="1","first_name"="Jimmy","last_name"="Reyes","email"="[email protected]","date"="12/29/2016","opt-in"="FALSE"
MU34T3<tab>"id"="2","first_name"="Doris","last_name"="Wood","email"="[email protected]","date"="04/22/2016,"opt-in"="0"
I will really appreciate any help/ideas/pointers.
Thanks
f1.close()is important?with open...construct, it should be closed automatically when you exit the block.