Topics covered

Python

Friday, 18 September 2020

How To Parse CSV File And Print The Output In Python

As a developer, we all know the importance of CSV files when it comes to storing and sharing data. Every developer has to go through this programming situation where they have to perform multiple operations on data and they have to use CSV files to make the data operation easy.

So before starting and knowing how to parse a CSV file in Python. let's take a look at what is CSV file.

What Is CSV File:

A CSV file is a file where data is stored in text or tabular format with fields separated by a delimiter, the delimiter could be anything like comma(','), tab('\t'), space('\s'), semicolon(';'), etc. CSV files are used by organizations when they have to import or export a huge amount of data.CSV file has made importing data from a program and exporting data to spreadsheets and databases very easy and convenient for developers. Multiple languages that support text file input and string operations  can work with CSV files

As we are now, clear with what CSV file is. let's proceed further and learn how to read CSV file in Python

Parsing A CSV File In Python:

Python provides an inbuilt CSV module to do read and write operations on the CSV file. To use that module we need to first import a CSV package using the command "import csv"

This CSV module has a reader and a writer object. 

Below is the code to read the CSV file

import csv

def parse_csv():

    #Parse CSV In Python
with open('sample_csv.csv', 'r') as csv_file:
reader = csv.reader(csv_file)
 

So in the above mentioned code if you see

A CSV file is open as a text file using an in-built open() function in read mode ('r') which in turn creates and pass a file object to the reader for further operation.

Below is the full code to parse a CSV file and output:

Code:

import csv

def parse_csv():


with open('sample_csv.csv', 'r') as csv_file:
reader = csv.reader(csv_file)

for row in reader:
print(row)


#main function
def main():
parse_csv()


if __name__ == '__main__':
main()

Output:

["'empid'", "'firstName'", "'Company'", "'Telephone'"]

["'1'", " 'employee1'", " 'company1'", "'1234'"]

["'2'", " 'employee2'", " 'company2'", "'5789'"]

["'3'", " 'employee3'", " 'company3'", "'4659'"]





No comments:

Post a Comment