How to read/write CSV files in Python

how-to-read-write-csv-files-in-python-csv-module

In this tutorial, we’re gonna look at way to use csv module to read, write CSV files in Python program.

CSV files

CSV stands for ‘comma-separated values’. CSV file is a spreadsheet stored as plain-text file.
Each line in a CSV file represents a row, and commas separate cells in the row.

For example:

Instead of commas, cells could be separated with tab characters:

CSV file is simple than Excel spreadsheet because it doesn’t have:
– types, everything is just a string
– font size or color
– multiple worksheets
– cell widths and heights
– merge cells
– images or charts

Read CSV file in Python

You can follow these steps to read data from a CSV file:
– import csv module
– open CSV file using open() function
– create a Reader object that lets you iterate over rows
– access values in the Reader object by:
+ convert it to a plain Python list using list() function
+ use for-loop (avoid loading the entire file into memory at once)

Remember that we can loop over Reader object only once.
To reread the CSV file by for-loop, we must create Reader object again.

Write CSV file in Python

You can follow these steps to write data to a CSV file:
– import csv module
– create new CSV file using open() function in write mode
– create a Writer object using csv.writer() function
– use Writer object writerow() method to write a line (form of a list). The return value of writerow() is the number of characters for that row (including newline characters).

Result in grokonez.csv file:

*Note: On Windows, newline keyword argument of open() function helps us avoid double-spaced when writing a new row in the output CSV file.

If we want to separate cells and end rows with a specific character, just pass delimiter and lineterminator as keyword arguments of csv.writer() function:


Result in grokonez.csv file:


By grokonez | February 4, 2019.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*