6. Python CSV
6. 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.
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).
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.
Jack 23 Doctor
Miller 22 Engineer
import csv
reader = csv.reader(file)
print(row)
Output:
.. .. ...
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.
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.
import csv
print(row)
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.
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.
import csv
writer = csv.writer(file)
When we run the above program, a protagonist.csv file is created with the following content:
SN,Movie,Protagonist
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"],
writer = csv.writer(file)
writer.writerows(csv_rowlist)
Here, our 2-dimensional list is passed to the writer.writerows() method to write the content of the list to
the CSV file.
import csv
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