How to Import CSV in Python

Sometimes you may need to import CSV file in Python for data analysis and reporting. There are different ways to load CSV data in python. In this article, we will look at how to import CSV using CSV reader, and using pandas libraries.


How to Import CSV in Python

Here are the steps to import csv in python. Let us say you have the csv file data.csv.

id,product,amount
1,'A',100
2,'B',125
3,'C',150

Also read : How to Sort Dictionary By Key in Python


Using CSV Reader

Let us say our file is located at C:\data.txt. Here are the steps to import CSV using csv reader. Replace the path below with your file path. Also, use backward slash in file path for Windows, and use forward slash in file path for Linux.

import csv
with open('c:\data.csv', newline='') as csvfile:
     file_reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
     for row in file_reader:
         print(' '.join(row))
id product amount
1 'A' 100
2 'B' 125
3 'C' 150

Let us look at the above code in detail.

First, we import csv library that contains python functions to work with csv files.

Next, open the file and create a file reader that allows us to loop through the csv file, line by line, using the row iterator. We print each row’s values by using join() function on the row to join all its values into a single string separated by ‘ ‘ (space).

Also read : How to Install Tomcat in Ubuntu


Using pandas

Pandas is a powerful python library meant for data analysis. You can easily import csv file using pandas as shown below. Replace the path below with your file path. Also, use backward slash in file path for Windows, and use forward slash in file path for Linux.

import pandas 
file = pandas.read_csv (r'c:\data.csv') 
print(file)
1 'A' 100
2 'B' 125
3 'C' 150

That’s it. CSV file now will be imported in python for you.

Also read : How to Sort List in Python