Reading a CSV file

Python has an in-built module, csv, which we are going to use here to work with CSV files. We will use the csv.reader module to read a CSV file. Create a script called csv_read.py and write the following content in it:

import csv

csv_file = open('test.csv', 'r')
with csv_file:
read_csv = csv.reader(csv_file)
for row in read_csv:
print(row)

 Run the script and you will get the following output:

student@ubuntu:~$ python3 csv_read.py

Following is the output:

['Region', 'Country', 'Item Type', 'Sales Channel', 'Order Priority', 'Order Date', 'Order ID', 'Ship Date', 'Units Sold']
['Sub-Saharan Africa', 'Senegal', 'Cereal', 'Online', 'H', '4/18/2014', '616607081', '5/30/2014', '6593']
['Asia', 'Kyrgyzstan', 'Vegetables', 'Online', 'H', '6/24/2011', '814711606', '7/12/2011', '124']
['Sub-Saharan Africa', 'Cape Verde', 'Clothes', 'Offline', 'H', '8/2/2014', '939825713', '8/19/2014', '4168']
['Asia', 'Bangladesh', 'Clothes', 'Online', 'L', '1/13/2017', '187310731', '3/1/2017', '8263']
['Central America and the Caribbean', 'Honduras', 'Household', 'Offline', 'H', '2/8/2017', '522840487', '2/13/2017', '8974']
['Asia', 'Mongolia', 'Personal Care', 'Offline', 'C', '2/19/2014', '832401311', '2/23/2014', '4901']
['Europe', 'Bulgaria', 'Clothes', 'Online', 'M', '4/23/2012', '972292029', '6/3/2012', '1673']
['Asia', 'Sri Lanka', 'Cosmetics', 'Offline', 'M', '11/19/2016', '419123971', '12/18/2016', '6952']
['Sub-Saharan Africa', 'Cameroon', 'Beverages', 'Offline', 'C', '4/1/2015', '519820964', '4/18/2015', '5430']
['Asia', 'Turkmenistan', 'Household', 'Offline', 'L', '12/30/2010', '441619336', '1/20/2011', '3830']

In the preceding program, we opened our test.csv file as csv_file. Then, we used the csv.reader() function to extract the data into the reader object, which we can iterate over to get each line of our data. Now, we are going to look at the second function, csv.Writer()

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset