To write data in a csv file, we use the csv.writer module. In this section, we will store some data into the Python list and then put that data into the csv file. Create a script called csv_write.py and write the following content in it:
import csv
write_csv = [['Name', 'Sport'], ['Andres Iniesta', 'Football'], ['AB de Villiers', 'Cricket'], ['Virat Kohli', 'Cricket'], ['Lionel Messi', 'Football']]
with open('csv_write.csv', 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerows(write_csv)
print(write_csv)
Run the script and you will get the following output:
student@ubuntu:~$ python3 csv_write.py
Following is the output:
[['Name', 'Sport'], ['Andres Iniesta', 'Football'], ['AB de Villiers', 'Cricket'], ['Virat Kohli', 'Cricket'], ['Lionel Messi', 'Football']]
In the preceding program, we created a list named write_csv with a Name and its Sport. Then, after creating the list, we opened the newly created csv_write.csv file and inserted the write_csv list into it using the csvWriter() function.