sampleqa.in tutorial, Python Programming  tutorial,Python time module

Python CSV Module Example


     CSV(Comma seperated values) is a textual data Python CSV related functions exists in csv module. This module has various methods to read CSV data, and Write into a csv File

CSV file fields can be commonly seperated by , comma, semicolon,colon, by tab space, or any other character you choose, and each line terminated by new line '\n' '\r\n' character


Import CSV Module
      		import csv
      
In This tutorial , we used stocks.csv file for demo purpose.

CSV file has first line is header

Second line onwards,it contains actual data, each field is seperated by comma. The followng CSV file has Stock Symbol,price,date purchased ,at time, change and volume of stocks

Symbol,Price,Date,Time,Change,Volume
"CAT",39.48,"6/11/2007","9:36am",-0.18,181800
"BAT",71.38,"6/11/2007","9:36am",-0.15,195500
"RAT",62.58,"6/11/2007","9:36am",-0.46,935000
"MAT",98.31,"6/11/2007","9:36am",+0.12,104800
"DOT",53.08,"6/11/2007","9:36am",-0.25,360900
"SAT",78.29,"6/11/2007","9:36am",-0.23,225400	
	

Reading Unix Password File

     Unix/Linux password file usually located in /etc/passwd. Here Each field is sepectrated by 'colon'

This file contains user name, group, type of shell,home directory etc.,

		fp=open('/etc/passwd')
		reader=csv.reader(fp,delimiter=':',quoting=csv.QUOTE_NONE)
		for row in reader:
		   print(row)
	

CSV Dialects

    CSV dialects supports three forms 'excel', 'excel-tab','unix'

excel dialect
	sp,ps,123,456,789
	
excel-tab dialect
	sp	ps	123	456	789
	
unix dialect
	"sp","ps","123","456","789"
	

ADS