0% found this document useful (0 votes)
2 views

6. Python CSV

The document explains the CSV (Comma-Separated Values) format, which is used for storing tabular data in plaintext with fields separated by commas. It details how to read and write CSV files in Python using the csv.reader() and csv.writer() functions, providing examples for both comma and tab delimiters. Additionally, it highlights the advantages of CSV format, including its simplicity and compatibility with spreadsheet applications.

Uploaded by

meensharma77
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

6. Python CSV

The document explains the CSV (Comma-Separated Values) format, which is used for storing tabular data in plaintext with fields separated by commas. It details how to read and write CSV files in Python using the csv.reader() and csv.writer() functions, providing examples for both comma and tab delimiters. Additionally, it highlights the advantages of CSV format, including its simplicity and compatibility with spreadsheet applications.

Uploaded by

meensharma77
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python CSV

The CSV is sort for Comma-Separated Values. The CSV format refers to a tabular data that has been
saved as plaintext where data is separated by commas.

 Each row of the table is stored in one row i.e., the number of rows in a CSV file are equal to
number of rows in the table.
 The field-value of a row is stored together with commas after every field value; but after the last
field’s value in a line/row no comma is given just end of line.

The CSV format is popular as it offers following advantages:

 A simple and compact format for data storage


 A Common format for data interchange.
 It can be opened in a popular spreadsheet package like MS-Excel, Calc etc.

We can create a CSV file yourself by saving data of an MS-Excel file in CSV format using Save As
command from File tab/menu and selecting Save As Type as CSV Formart).

1. Create simple table in Ms-Excel

2. Go to Save As then Other Formats

3. Give location and file name in File name and select save as type and then select CSV (Comma
Delimited)
Reading CSV files Using csv.reader()

To read a CSV file in Python, we can use the csv.reader() function. Suppose we have a csv file named
people.csv in the current directory with the following entries.

Name Age Profession

Jack 23 Doctor

Miller 22 Engineer

Let's read this file using csv.reader():

Example 1: Read CSV Having Comma Delimiter

import csv

with open('people.csv', 'r') as file:

reader = csv.reader(file)

for row in reader:

print(row)

Output:

['Name', 'Age', 'Profession']

['Jack', '23', 'Doctor']

['Miller', '22', 'Engineer']

Here, we have opened the people.csv file in reading mode using:

with open('people.csv', 'r') as file:

.. .. ...

To learn more about opening files in Python, visit: Python File Input/Output

Then, the csv.reader() is used to read the file, which returns an iterable reader object.
The reader object is then iterated using a for loop to print the contents of each row.

In the above example, we are using the csv.reader() function in default mode for CSV files having comma
delimiter.

However, the function is much more customizable.

Suppose our CSV file was using tab as a delimiter. To read such files, we can pass optional parameters to
the csv.reader() function. Let's take an example.

Example 2: Read CSV file Having Tab Delimiter

import csv

with open('people.csv', 'r',) as file:

reader = csv.reader(file, delimiter = '\t')

for row in reader:

print(row)

Notice the optional parameter delimiter = '\t' in the above example.

The complete syntax of the csv.reader() function is:

csv.reader(csvfile, dialect='excel', **optional_parameters)

As you can see from the syntax, we can also pass the dialect parameter to the csv.reader() function. The
dialect parameter allows us to make the function more flexible. To learn more, visit: Reading CSV files in
Python.

Writing CSV files Using csv.writer()

To write to a CSV file in Python, we can use the csv.writer() function.

The csv.writer() function returns a writer object that converts the user's data into a delimited string. This
string can later be used to write into CSV files using the writerow() function. Let's take an example.

Example 3: Write to a CSV file

import csv

with open('protagonist.csv', 'w', newline='') as file:

writer = csv.writer(file)

writer.writerow(["SN", "Movie", "Protagonist"])

writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])

writer.writerow([2, "Harry Potter", "Harry Potter"])

When we run the above program, a protagonist.csv file is created with the following content:

SN,Movie,Protagonist

1,Lord of the Rings,Frodo Baggins

2,Harry Potter,Harry Potter

In the above program, we have opened the file in writing mode.


Then, we have passed each row as a list. These lists are converted to a delimited string and written into
the CSV file.

Example 4: Writing multiple rows with writerows()

If we need to write the contents of the 2-dimensional list to a CSV file, here's how we can do it.

import csv

csv_rowlist = [["SN", "Movie", "Protagonist"], [1, "Lord of the Rings", "Frodo Baggins"],

[2, "Harry Potter", "Harry Potter"]]

with open('protagonist.csv', 'w') as file:

writer = csv.writer(file)

writer.writerows(csv_rowlist)

The output of the program is the same as in Example 3.

Here, our 2-dimensional list is passed to the writer.writerows() method to write the content of the list to
the CSV file.

Example 5: Writing to a CSV File with Tab Delimiter

import csv

with open('protagonist.csv', 'w') as file:

writer = csv.writer(file, delimiter = '\t')

writer.writerow(["SN", "Movie", "Protagonist"])

writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])

writer.writerow([2, "Harry Potter", "Harry Potter"])

Notice the optional parameter delimiter = '\t' in the csv.writer() function.

The complete syntax of the csv.writer() function is:

csv.writer(csvfile, dialect='excel', **optional_parameters)

Similar to csv.reader(), you can also pass dialect parameter the csv.writer() function to make the
function much more customizable. To learn more, visit: Writing CSV files in Python

You might also like