Example 1: create csv file python
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('protagonist.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(row_list)
Example 2: array storing in csv file by python
import numpy as np
import csv
arr1 = [i for i in range(500)]
arr2 = [i for i in range(1000)]
arr3 = [i for i in range(2000)]
with open('record.csv', 'a') as record_append:
np.savetxt(record_append, np.asarray([arr1]), delimiter=',')
np.savetxt(record_append, np.asarray([arr2]), delimiter=',')
np.savetxt(record_append, np.asarray([arr3]), delimiter=',')
two_dim_arr = []
with open('record.csv', 'r') as record_read:
reader = csv.reader(record_read)
for i, each_arr in enumerate(reader):
two_dim_arr.append([eval(each) for each in each_arr])
for each_line in two_dim_arr:
print(each_line)
Example 3: python save as csv
import numpy as np
np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')
Example 4: Write a table to CSV file python
header = [re.sub(' +',' ',i[0][:-1].replace('\n', ' ')) for i in optionsTable[0]]
with open('test.csv', 'w') as fp:
writer = csv.writer(fp, delimiter=',')
writer.writerow(header)
for row in optionsTable:
writer.writerow([i[1] for i in row])