Python Create CSV File Example Tutorial

Hi Guys,
This tutorial will provide example of how to create csv file in python. I’m going to show you about python writing csv file example. We will use python output to csv file example. you will learn how to create csv file in python 3.
In this illustration, we'll make a demo.csv file with fields for ID, Name, and Email. To generate a CSV file, we will utilise the open(), writer(), writerow(), writerows(), and close() functions. The following justifies our use of functions.
1. open() creates a CSV file if one doesn't already exist.
2. Writer() creates a CSV file object to allow for the addition of new rows.
3. Write a single row with a header using the writerow() method.
4. writerows(): it will write multiple rows with list.
5. close(): it will close created new csv file object.
So let's see bellow example:
Example 1:
main.pyimport csv # open the file in the write mode f = open('demo.csv', 'w') # create the csv writer writer = csv.writer(f) header = ['ID', 'Name', 'Email'] data = [ [1, 'Bhavesh Sonagra', '[email protected]'], [2, 'Nikhil Patel', '[email protected]'], [3, 'Piyush Kamani', '[email protected]'] ] # write the header writer.writerow(header) # write a row to the csv file writer.writerows(data) # close the file f.close()Output

It will help you....