How to create CSV file in Python
In this tutorial, we will show writing a list into a CSV file in Python programs.
- The first way is using the Pandas library
- The second way is by using the CSV module
First way – Using CSV to create a CSV file based on a list
For this program, we have created a list of employees for the demo only.
First of all, import the csv:
import csv
This is followed by creating a list of employees with Id, Employee Name, and Salary:
row_list = [["empId", "Employee Name", "Salary"], [1, "Mike", "$5,000.00"], [2, "Michelle", "$4,500.00"], [3, "Ben", "$6,000.00"], [4, "Shabee", "$4,500.00"], [5, "Mina", "$3,000.00"] ]
The “With” statement is used where we used the open method and provided the CSV file name where we want to store the list.
If the file does not exist, a new file is created.
See the complete program below that uses writerows() method as follows:
import csv #Data in list to be saved in CSV file emp_list = [["empId", "Employee Name", "Salary"], [1, "Mike", "$5,000.00"], [2, "Michelle", "$4,500.00"], [3, "Ben", "$6,000.00"], [4, "Shabee", "$4,500.00"], [5, "Mina", "$3,000.00"] ] with open('test123.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(emp_list)
Result:
As we executed the above program, a file namely test123.csv is created in the same directory where the Python code file exists.
When we open this file in the notepad, this is how it looks:
The same file in MS Excel:
Second way – using Pandas to write a list to a CSV file
In this Python program, we are using the Pandas library to save the list into a new CSV file.
Include Pandas in your program:
Create a list that you want to save in a file as CSV.
We are using the same list as used in the above program.
Specify list and column names in the Data frame:
Use the data frame to_csv method:
Complete program:
import pandas as pd #Data to be saved in CSV file emp_list = [ [1, "Mike", "$5,000.00"], [2, "Michelle", "$4,500.00"], [3, "Ben", "$6,000.00"], [4, "Shabee", "$4,500.00"], [5, "Mina", "$3,000.00"] ] df_emp = pd.DataFrame (emp_list, columns = ['emp_id', 'Employee Name', 'Salary']) #Save list to CSV file df_emp.to_csv('emp_tst.csv', index=False)
Result:
A new file emp_tst.csv should be generated in the same directory where the code file is located.