Reading & Writing CSV with Python
CSV files are quite common these days owing to the fact that CSV files are simple text and make data transfer between different systems very easy. CSV stands for Comma Separated Values, i.e. the fields are separated by comma, so there exists similar formats where the separator is a different character like tab, or semi-colon. We have seen working with CSV in Perl & PHP, so why not in Python.
Python 2.4 onwards CSV reading and writing was made easier by inclusion on an in-built module csv, the module has reader & writer objects for reading & writing CSV files respectively.
Now, let's get our hands dirty with some code.
First let's look at a very basic example, which will read a CSV file and print out the fields:
Now, let us look at a scenario where the delimiter is : instead of comma, a good example of such a file is /etc/passwd:
Quoting is required when any field value contains the delimiter character, we'll look at it in the next section.
A writing example:
Here's the output:
As you can see the field value that contained a [B],[B] was quoted automatically.
|All times are GMT +5.5. The time now is 02:07.|