Home / Computer Science / Data Structures / Read and write with file csv in Python

Read and write with file csv in Python

Print Friendly, PDF & Email

It is possible to read and write CSV (comma separated values) files using Python 2.4 Distribution. Like most languages, file operations can be done with Python. Writing a CSV file with Python can be done by importing the CSV module and creating a write object that will be used with the WriteRow Method. Reading a CSV file can be done in a similar way by creating a reader object and by using the print method to read the file. As file operations require advanced concepts, some knowledge of programming with Python is required to read and write the CSV (comma separated values) files.

Python Www.python.org, version 2.4 supports the de facto CSV format (comma-separated values: ). The Reference Library is very helpful when learning to use Python. Here are some additional tips to get you started.

Prerequisites

-> Knowledge of Python -> Python 2.4 Distribution

Writing a CSV file

Start by importing the CSV module:

We will define an object “writer” (named c), which can later be used to write the CSV file.

Now we will apply the method to write a row. Writerow The method takes one argument – this argument must be a list and each list item is equivalent to a column. Here, we try to make an address book:

Then we will save all entries in this way.

Reading a CSV file

First just create an object reader (we will give it a name: cr).

And here we get each row (in the form of a list of columns) as follows:

We can of course extract a precise entry of a row with the index:

 

comments

About Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.