Friday, April 19, 2024
HomejQuery2 Methods to Create Listing to CSV File in Python

2 Methods to Create Listing to CSV File in Python


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:



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:



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:

Python-csv-output

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:



Consequence:

A brand new file emp_tst.csv needs to be generated in the identical listing the place the code file is positioned.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments