Topics covered

Python

Sunday, 20 September 2020

How To Write A CSV File In Python

In the previous post, we learnt about reading a CSV file in Python. Now in this post, we will learn how to write data into CSV using python's inbuilt writer object.

Writing data to CSV files is very easy and convenient. In Python to write a data or any delimited text to CSV is possible using an inbuilt module name CSV. It has a Writer class i.e. "csv.writer" that returns a writer object.

This writer object has two methods one helps to write one row at a time and another method helps to insert multiple rows at a time. 

In this post we will see writing CSV files using both the methods:

Writing CSV File Using writerow() Method

This method will let you write row-wise data at a time. So let's say we want to write the below data to csv

header=["id", "language", "company"]
row1=["1", "Python", "Development"]
row2=["2", "HTML", "Testing"]
row3=["3", "Java", "Coding"]

So to write the above-mentioned row data, I have defined a write_csv function as mentioned below

def write_csv():
    header = ["id", "language", "company"]
row1 = ["1", "Python", "Development"]
row2 = ["2", "HTML", "Testing"]
row3 = ["3", "Java", "Coding"]

with open('sample_csv1.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(header)
writer.writerow(row1)
writer.writerow(row2)

#main function
def main():
write_csv()


Writing CSV File Using writerows() Method

writerows() method will help to write multiple rows. 

Let's say we have below data in form of lists of lists and we need to write it in CSV

header=["id", "language", "company"]
rows=[["1", "Python", "Development"],
            ["2", "HTML", "Testing"],
            ["3", "Java", "Coding"]]

here how we do it, to write multiple rows using the writer.writerows()

def write_multiple_rows_csv():
header = ["id", "language", "company"]
rows = [["1", "Python", "Development"],
["2", "HTML", "Testing"],
["3", "Java", "Coding"]]
with open('sample_csv1.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(header)
writer.writerows(rows)

#main function
def main():
write_multiple_rows_csv()


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'"]