Working with CSV file Using Python

About CSV

Comma-separated values are known as CSV. It is the simplest form of storing data in tabular form as plain text. Data Scientists need to know how to work with CSV data because most of their activities involve CSV data.In CSV files, the first line contains the field/feature names.

The following lines of the file are observations/records. The values of a record are separated by “comma.”


Here we have a file named “annual-energy-survey-demo-csv.csv” using this CSV file, we will try to learn how to  read and write the CSV files.


In this article, I'll explain in detail how you can read and write CSV files in Python.  


# Import the csv library

import csv


# Open the CSV file

file = open('/content/drive/MyDrive/annual-enpr-survey-demo-csv.csv')

type(file)

output:io.TextIOWrapper


# Use the csv.reader object to read the CSV file 

csvreader = csv.reader(file)


# Extract the fields names

csv_header = []

csv_header = next(csvreader)

print(header)

 

Output:

['Year', 'Industry_aggregation', 'Industry_code']


#Extract the rows or records

csv_rows = []

for each_row in csvreader:

        csv_rows.append(each_row)

print(csv_rows)

Output:


[['2019', 'Level 4', 'AA111'],

 ['2020', 'Level 5', 'AA112'],

 ['2020', 'Level 4', 'AA111'],

 ['2019', 'Level 2', 'AA156'],

 ['2020', 'Level 5', 'AA111'],

 ['2020', 'Level 4', 'AA112'],

 ['2021', 'Level 2', 'AA111'],

 ['2020', 'Level 4', 'AA111'],

 ['2021', 'Level 5', 'AA111'],

 ['2020', 'Level 4', 'AA111'],

 ['2021', 'Level 4', 'AA110'],

 ['2020', 'Level 5', 'AA111'],

 ['2020', 'Level 4', 'AA114'],

 ['2020', 'Level 5', 'AA111'],

 ['2021', 'Level 4', 'AA113'],

 ['2020', 'Level 4', 'AA116'],

 ['2018', 'Level 5', 'AA111'],

 ['2021', 'Level 2', 'AA115'],

 ['2020', 'Level 4', 'AA116'],

 ['2020', 'Level 5', 'AA111']]


#Close the file

file.close()

Comments

Popular posts from this blog

Validation Code For Phone Number Using preg_match() in Php

Writing data to a file using Python

Simple HTML Form Elements For Registration Page Example