Switch to full style
Python Technology Tutorials Written By Members.
Post a reply

How to read and write to CSV file from python

Sun Jul 22, 2012 2:39 pm

CVS file is well known text transfer type, CVS stands for “comma separated values”. In this article will be working on CVS files using Python for reading and writing:
First how to read a CVS file from Python, in the following simple example we are reading CVS file and printing its content:
Code:
import csv
mycsv_reader 
= csv.reader(open("codemiles.csv", "rb"))
for dataSample in mycsv_reader:
    print dataSample

We can also read the file even if a different delimiter is used for example delimiter “:”
Code:
import csv
## get the reader object, and specify no quoting
mycsv_reader = csv.reader(open("codemiles.txt", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
for dataSample in mycsv_reader:
    print dataSample


Quoting is important to handle the cases when any field value contains the delimiter character. Now, what about writing to CVS file, how we can do that? Following example illustrate an example for it:
Code:
import csv

## get writer object
mycsv_writer = csv.writer(open('codemiles.csv', 'wb'), quoting=csv.QUOTE_MINIMAL)

## write rows to CVS file
mycsv_writer.writerow(['Cairo','CA'])
mycsv_writer.writerow(['Newyork','NY'])
csv_writer.writerow([Poor, saeed','PS]) 



the output of this snippet will be printed in the codemiles.cvs file as follows :
Code:
Cairo, CA
Newyork , NY
“Poor, saeed”, PS



You many notice at last row automatically the word “Poor, saeed” was QUOTED.



Post a reply
  Related Posts  to : How to read and write to CSV file from python
 File write read     -  
 Read and Write to file using ASP     -  
 Read and write CSV file     -  
 Write and Read to File In Java Example     -  
 Write to file using php     -  
 Write Vector list to File     -  
 read from file in C++     -  
 Read csv file     -  
 javascript read file     -  
 File read by char     -  

Topic Tags

Python Files and I/O