How one can create CSV file in Python
On this tutorial, we are going to present writing a listing right into a CSV file in Python applications.
- The primary method is utilizing the Pandas library
- Second method is through the use of the CSV module
First method – Utilizing CSV to create a CSV file primarily based on a listing
For this program, now we have created a listing of workers for the demo solely.
Step 1:
Initially, import the csv:
import csv
Step 2:
That is adopted by creating a listing of workers with Id, Worker Title, and Wage:
|
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”]
] |
Step 3:
With assertion is used the place we used the open methodology and offered the CSV file title the place we wish to retailer the listing.
If the file doesn’t exist, a brand new file is created.
See the whole program under that makes use of writerows() methodology as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
import csv
#Information in listing 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:
author = csv.author(file)
author.writerows(emp_list) |
Consequence:
As we executed the above program, a file particularly test123.csv is created in the identical listing the place the Python code file exists.
As we open this file within the notepad, that is the way it seems:
The identical file in MS Excel:
Second method – utilizing Pandas to write down a listing to a CSV file
On this Python program, we’re utilizing the Pandas library to save lots of the listing into a brand new CSV file.
Step 1:
Embody Pandas in your program:
import pandas as pd
Step 2:
Create a listing that you just wish to save in a file as CSV.
We’re utilizing the identical listing as used within the above program.
Step 3:
Specify listing and column names within the Information body:
df_emp = pd.DataFrame (emp_list, columns = [’emp_id’, ‘Employee Name’, ‘Salary’])
Step 4:
Use the information body to_csv methodology:
df_emp.to_csv(‘csv_emp.csv’, index=False)
Full program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
import pandas as pd
#Information 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 listing to CSV file
df_emp.to_csv(’emp_tst.csv’, index=False) |
Consequence:
A brand new file emp_tst.csv needs to be generated in the identical listing the place the code file is positioned.