Python Data Persistence – csv module

Python Data Persistence – csv module

Dictreader python: The Comma Separated Values (CSV) format is very widely used to import and export data in spreadsheets and RDBMS tables. The csv module, another built-in module in Python’s standard library, presents the functionality to easily convert Python’s sequence object in CSV format and write to a disk file. Conversely, data from CSV files is possible to be brought in Python namespace. The reader and writer classes are defined in this module that performs read/write operations on CSV files. In addition, this module also has DictReader and DxctWriter classes to work with Python’s dictionary objects.

The object of the writer class is obtained by the writer () constructor which needs a file object having ‘w’ mode enabled. An optional ‘dialect’ parameter is given to specify the implementation type of CSV protocol, which is by default ‘excel’ – the format preferred by MS Excel spreadsheet software. We are now in a position to write one or more rows to the file represented by the writer object.

Example

>>> import csv
>>> data=[('TV', 1 Samsung',25000) , ( 'Comput-
er1 'Dell40000),('Mobile', 'Redmi ',15000)]
> > > file=open (' pricelist .csv' , 'w' , newline='')
>>> obj =csv. writer (file)
>>> #write single row
>>> obj.writerow(data[0])
>>> #write multiple rows
> > > obj.writerows(data [1:])
> > > file . close ( )

Note that, open( ) function needs the newline=’ ‘ parameter to correctly interpret newlines inside quoted fields. The ‘pricelist.csv’ should be created in the current working directory. Its contents can be verified by opening in any text editor, as per your choice.
The reader object, on the other, hand returns an iterator object of rows in the CSV file. A simple for loop or next() function of an iterator can be used to traverse all rows.

Example

>>> file=open ('pricelist .csv' , ' r ' newline=' ' )
>>> obj =csv. reader (file)
>>> for row in obj:
print (row)
['TV', 'Samsung', 25000']
['Computer', 'Dell , '40000']
['Mobile', 'Redmi' '15000']
>>>

The csv module offers powerful DictWriter and DictReader classes that can deal with dictionary objects. DictWriter maps the sequence of dictionary objects to rows in the CSV file. As always, the DictWriter constructor needs a writable file object. It also needs a fieldnames parameter whose value has to be a list of fields. These fields will be written as a first row in the resultant CSV file. Let us convert a list of tuples, in the above example, to a list of diet objects and send it to csv format using the DictWriter object.

Example

>>> data=[{'product':'TV', 'brand1:1 Samsung ','price':25000}, {'product':'Computer','br and':'Dell','price':40000},{'product':'Mo¬bile ', 'brand' :'Redmi', 'price' :15000 } ]
>>> file=open (' pricelist. csv' , ' w' , newline= ' ')
>>> fields=data [0] .keys()
>>> obj =csv.DictWriter (file,fields)

The DictWriter’s write header () method uses fieldnames parameter to write header row in CSV file. Each row following the header contains the keys of each dictionary item.

Example

>>> obj.writeheader() 
>>> obj.writerows(data)
>>> 'file . close ()

The resulting ‘pricelist.csv’ will show data, as follows:

Example

product,brand,price 
TV,Samsung, 2 5000 
Computer,Dell ,4 0000 
Mobile,Redmi,15000

Reading rows in dictionary formation is easy as well. The DictReader object is obtained from the source CSV file. The object stores strings in the first row in field name attributes. A simple for loop can fetch subsequent rows. However, each row returns an OrderedDict object. Use diet () function to obtain a normal dictionary object out of each row.

Example

>>> file=open ('pricelist. csvr ,newline='')
>>> obj=csv.DictReader (file)
>>> obj .fieldnames
['product1, 'brand', 'price']
>>> for row in obj:
print (diet(row))
{'product': 'TV', 'brand': 'Samsung', price': '25000'}
{'product': 'Computer', 'brand' 'Dell ' , ' price' : '40000'}
{'product': 'Mobile', 'brand': Redmi' 'price': ' 15000'}