1# This action requires the 'csv' module
2import csv
3
4# The basic usage is to first define the rows of the csv file:
5row_list = [["SN", "Name", "Contribution"],
6 [1, "Linus Torvalds", "Linux Kernel"],
7 [2, "Tim Berners-Lee", "World Wide Web"],
8 [3, "Guido van Rossum", "Python Programming"]]
9
10# And then use the following to create the csv file:
11with open('protagonist.csv', 'w', newline='') as file:
12 writer = csv.writer(file)
13 writer.writerows(row_list)
14# This will create a csv file in the current directory
1import csv
2
3with open('names.csv', 'w') as csvfile:
4 fieldnames = ['first_name', 'last_name']
5 writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
6
7 writer.writeheader()
8 writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
9 writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
10 writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
11
1with open(r'c:\dl\FrameRecentSessions.csv') as csv_file:
2 csv_reader = csv.reader(csv_file, delimiter=',')
3 line_count = 0
4 for row in csv_reader:
5 if line_count == 0:
6 print(f'Column names are {", ".join(row)}')
7 line_count += 1
8 else:
9 print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
10 line_count += 1
11 print(f'Processed {line_count} lines.')
1import numpy as np
2np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')
1>>> import csv
2>>> with open('eggs.csv', newline='') as csvfile:
3... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
4... for row in spamreader:
5... print(', '.join(row))
6Spam, Spam, Spam, Spam, Spam, Baked Beans
7Spam, Lovely Spam, Wonderful Spam
8