Total members 11867 |It is currently Sun Jan 23, 2022 3:05 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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.



_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 1 post ] 

  Related Posts  to : How to read and write to CSV file from python
 Read and Write to file using ASP     -  
 Read and write CSV file     -  
 File write read     -  
 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
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com