SlideShare a Scribd company logo
Python
Lecture - 11
- Ravi Kiran Khareedi
CSV Module
• CSV - Comma Separated Value
• Using CSV module we can read and write the
CSV files.CSV files.
• CSV files are usually delimited by , . But any
other delimited is possible
Reading a CSV
• csv.reader() – Reading data from the CSV file.
• The reader can be used as an iterator to process
import csvimport csv
f = open("countrylist.csv");
reader = csv.reader(f);
for row in reader:
print row;
f.close();
Writing a CSV
• csv.writer() – Writing a CSV file.
import csv
f = open("samplewrite.csv",'wb');f = open("samplewrite.csv",'wb');
a =
[["Name","Address","Phone"],["Alice","Hamburg","12345"],["Bob","Kiel","
31321"]];
writer = csv.writer(f);
writer.writerows(a);
f.close();
Another way to write
import csv
f = open("samplewrite.csv",'wb');
writer = csv.writer(f);
for i in range(10):
writer.writerow([i, "Name_"+str(i)]);
f.close();
Quoting
• There are four different quoting options, defined as constants
in the csv module.
• QUOTE_ALL Quote everything, regardless of type.
• QUOTE_MINIMAL Quote fields with special characters
(anything that would confuse a parser configured with the
same dialect and options). This is the default
(anything that would confuse a parser configured with the
same dialect and options). This is the default
• QUOTE_NONNUMERIC Quote all fields that are not integers
or floats. When used with the reader, input fields that are not
quoted are converted to floats.
• QUOTE_NONE Do not quote anything on output. When used
with the reader, quote characters are included in the field
values
Quoting Example
import csv
f = open("samplewrite.csv",'wb');
a = [["Name","Address","Phone"],["Alice","Hamburg","12345"],["Bob","Kiel","31321"]];
writer = csv.writer(f,quoting = csv.QUOTE_NONNUMERIC);
for i in range(10):
writer.writerow([i, "Name_"+str(i)]);
f.close();f.close();
f = open("samplewrite.csv",'rb');
reader = csv.reader(f, quoting = csv.QUOTE_NONNUMERIC);
for row in reader:
print row;
f.close();
TASK
• Try different combinations of QUOTE on
reader and writer.
Dialects
• No defined standard for CSV
• Hence Reader and Writer should be flexible
• So instead of passing all the parameters to the
reader and writer separately, they are grouped
into DIALECT object.
Dialect list
import csv
print csv.list_dialects();
Default: excel and excel_tab
excel : The excel class defines the usual propertiesexcel : The excel class defines the usual properties
of an Excel-generated CSV file. It is registered
with the dialect name 'excel'.
excel_tab : The excel_tab class defines the usual
properties of an Excel-generated TAB-delimited
file
Register a dialect
import csv
csv.register_dialect('pipes', delimiter='|')
f = open("sampleread.csv");f = open("sampleread.csv");
reader = csv.reader(f, dialect = 'pipes');
for row in reader:
print row;
f.close();
Dialect Parameters
• A dialect specifies all of the tokens used when parsing or
writing a data file.
• Every aspect of the file format can be specified, from the way
columns are delimited to the character used to escape a token.
Program to understand dialect
import csv
csv.register_dialect('escaped', escapechar='', doublequote=False, quoting=csv.QUOTE_NONE)
csv.register_dialect('singlequote', quotechar="'", quoting=csv.QUOTE_ALL)
#quoting_modes = dict( (getattr(csv,n), n) for n in dir(csv) if n.startswith('QUOTE_') )
for name in csv.list_dialects():
print 'nDialect: "%s"n' % name
dialect = csv.get_dialect(name)
print "Delimiter : " + str(dialect.delimiter) + " Skip Initial Space : " + str(dialect.skipinitialspace);
print "Doublequote: " + str(dialect.doublequote) +"Escapechar: " + str(dialect.escapechar);
print "Quote Char : " + str(dialect.quotechar) + " Line Terminator : " +
str(dialect.lineterminator);
print
Automatically Detecting Dialects
• For data where parameters are unknown.
• Sniffer class helps to understand the
parameters in the data.parameters in the data.
• (Lets see this later… )
TASK
• Given an array length 1 or more of ints, return
the difference between the largest and
smallest values in the list
• Input : [10, 3, 5, 6]• Input : [10, 3, 5, 6]
• Output: 7
TASK
• Given an array of ints, return True if the array
contains a 2 next to a 2 somewhere.
• Input / Output : [1, 2, 2] → True• Input / Output : [1, 2, 2] → True
Input / Output : [1, 2, 1, 2] → False
Input / Output : [2, 1, 2] → False
TASK
• Return the "centered" average of an array of ints,
which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the
array.
• If there are multiple copies of the smallest value,
ignore just one copy, and likewise for the largest value.ignore just one copy, and likewise for the largest value.
Use int division to produce the final average. You may
assume that the array is length 3 or more.
Input/Output : [1, 2, 3, 4, 100] → 3
Input/Output: [1, 1, 5, 5, 10, 8, 7] → 5
References
• http://pymotw.com/2/csv/
• https://docs.python.org/2/library/csv.html
• http://codingbat.com/python

More Related Content

PDF
Python functions
PDF
Built in exceptions
PDF
Python programming : Classes objects
PPTX
Python Scipy Numpy
PDF
What is Python Lambda Function? Python Tutorial | Edureka
PPS
String and string buffer
PPS
Wrapper class
PPTX
String, string builder, string buffer
Python functions
Built in exceptions
Python programming : Classes objects
Python Scipy Numpy
What is Python Lambda Function? Python Tutorial | Edureka
String and string buffer
Wrapper class
String, string builder, string buffer

What's hot (20)

PPTX
Chapter 05 classes and objects
PPTX
Python variables and data types.pptx
PDF
Functions and modules in python
PDF
Python programming : Strings
PDF
Python Class | Python Programming | Python Tutorial | Edureka
PPTX
Functions in Python
PDF
Generics
PDF
Python libraries
PDF
Introduction to Recursion (Python)
PPTX
Chapter 14 strings
PPTX
Introduction to the basics of Python programming (part 1)
PPT
Python ppt
PPTX
Methods in java
PDF
PPTX
Recursion with Python [Rev]
PPTX
Constructor in java
PDF
Python Programming
PPTX
Python Tutorial Part 1
PPTX
classes and objects in C++
Chapter 05 classes and objects
Python variables and data types.pptx
Functions and modules in python
Python programming : Strings
Python Class | Python Programming | Python Tutorial | Edureka
Functions in Python
Generics
Python libraries
Introduction to Recursion (Python)
Chapter 14 strings
Introduction to the basics of Python programming (part 1)
Python ppt
Methods in java
Recursion with Python [Rev]
Constructor in java
Python Programming
Python Tutorial Part 1
classes and objects in C++
Ad

Similar to Python - Lecture 11 (20)

PPTX
Moving Data to and From R
PPTX
ReadingWriting_CSV_files.pptx sjdjs sjbjs sjnd
PPTX
BINARY files CSV files JSON files with example.pptx
PPTX
Unit I - 1R introduction to R program.pptx
PPTX
Aggregate.pptx
KEY
R for Pirates. ESCCONF October 27, 2011
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PDF
CSV Files-1.pdf
PPTX
PPTX
CSV File Manipulation
PDF
Matlab lec1
PDF
Import Data using R
PPTX
Cs1123 3 c++ overview
Moving Data to and From R
ReadingWriting_CSV_files.pptx sjdjs sjbjs sjnd
BINARY files CSV files JSON files with example.pptx
Unit I - 1R introduction to R program.pptx
Aggregate.pptx
R for Pirates. ESCCONF October 27, 2011
Python basics
Python basics
Python basics
Python basics
Python basics
Python basics
Python basics
CSV Files-1.pdf
CSV File Manipulation
Matlab lec1
Import Data using R
Cs1123 3 c++ overview
Ad

More from Ravi Kiran Khareedi (11)

PDF
Python - Lecture 12
PDF
Python - Lecture 10
PDF
Python - Lecture 9
PDF
Python - Lecture 8
PDF
Python - Lecture 7
PDF
Python - Lecture 6
PDF
Python - Lecture 5
PDF
Python - Lecture 4
PDF
Python - Lecture 3
PDF
Python - Lecture 2
PDF
Python - Lecture 1
Python - Lecture 12
Python - Lecture 10
Python - Lecture 9
Python - Lecture 8
Python - Lecture 7
Python - Lecture 6
Python - Lecture 5
Python - Lecture 4
Python - Lecture 3
Python - Lecture 2
Python - Lecture 1

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Mushroom cultivation and it's methods.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
Teaching material agriculture food technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
A Presentation on Artificial Intelligence
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
cloud_computing_Infrastucture_as_cloud_p
Machine learning based COVID-19 study performance prediction
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Mushroom cultivation and it's methods.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Assigned Numbers - 2025 - Bluetooth® Document
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Spectral efficient network and resource selection model in 5G networks
Teaching material agriculture food technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A Presentation on Artificial Intelligence
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Accuracy of neural networks in brain wave diagnosis of schizophrenia
A comparative analysis of optical character recognition models for extracting...
cloud_computing_Infrastucture_as_cloud_p

Python - Lecture 11

  • 1. Python Lecture - 11 - Ravi Kiran Khareedi
  • 2. CSV Module • CSV - Comma Separated Value • Using CSV module we can read and write the CSV files.CSV files. • CSV files are usually delimited by , . But any other delimited is possible
  • 3. Reading a CSV • csv.reader() – Reading data from the CSV file. • The reader can be used as an iterator to process import csvimport csv f = open("countrylist.csv"); reader = csv.reader(f); for row in reader: print row; f.close();
  • 4. Writing a CSV • csv.writer() – Writing a CSV file. import csv f = open("samplewrite.csv",'wb');f = open("samplewrite.csv",'wb'); a = [["Name","Address","Phone"],["Alice","Hamburg","12345"],["Bob","Kiel"," 31321"]]; writer = csv.writer(f); writer.writerows(a); f.close();
  • 5. Another way to write import csv f = open("samplewrite.csv",'wb'); writer = csv.writer(f); for i in range(10): writer.writerow([i, "Name_"+str(i)]); f.close();
  • 6. Quoting • There are four different quoting options, defined as constants in the csv module. • QUOTE_ALL Quote everything, regardless of type. • QUOTE_MINIMAL Quote fields with special characters (anything that would confuse a parser configured with the same dialect and options). This is the default (anything that would confuse a parser configured with the same dialect and options). This is the default • QUOTE_NONNUMERIC Quote all fields that are not integers or floats. When used with the reader, input fields that are not quoted are converted to floats. • QUOTE_NONE Do not quote anything on output. When used with the reader, quote characters are included in the field values
  • 7. Quoting Example import csv f = open("samplewrite.csv",'wb'); a = [["Name","Address","Phone"],["Alice","Hamburg","12345"],["Bob","Kiel","31321"]]; writer = csv.writer(f,quoting = csv.QUOTE_NONNUMERIC); for i in range(10): writer.writerow([i, "Name_"+str(i)]); f.close();f.close(); f = open("samplewrite.csv",'rb'); reader = csv.reader(f, quoting = csv.QUOTE_NONNUMERIC); for row in reader: print row; f.close();
  • 8. TASK • Try different combinations of QUOTE on reader and writer.
  • 9. Dialects • No defined standard for CSV • Hence Reader and Writer should be flexible • So instead of passing all the parameters to the reader and writer separately, they are grouped into DIALECT object.
  • 10. Dialect list import csv print csv.list_dialects(); Default: excel and excel_tab excel : The excel class defines the usual propertiesexcel : The excel class defines the usual properties of an Excel-generated CSV file. It is registered with the dialect name 'excel'. excel_tab : The excel_tab class defines the usual properties of an Excel-generated TAB-delimited file
  • 11. Register a dialect import csv csv.register_dialect('pipes', delimiter='|') f = open("sampleread.csv");f = open("sampleread.csv"); reader = csv.reader(f, dialect = 'pipes'); for row in reader: print row; f.close();
  • 12. Dialect Parameters • A dialect specifies all of the tokens used when parsing or writing a data file. • Every aspect of the file format can be specified, from the way columns are delimited to the character used to escape a token.
  • 13. Program to understand dialect import csv csv.register_dialect('escaped', escapechar='', doublequote=False, quoting=csv.QUOTE_NONE) csv.register_dialect('singlequote', quotechar="'", quoting=csv.QUOTE_ALL) #quoting_modes = dict( (getattr(csv,n), n) for n in dir(csv) if n.startswith('QUOTE_') ) for name in csv.list_dialects(): print 'nDialect: "%s"n' % name dialect = csv.get_dialect(name) print "Delimiter : " + str(dialect.delimiter) + " Skip Initial Space : " + str(dialect.skipinitialspace); print "Doublequote: " + str(dialect.doublequote) +"Escapechar: " + str(dialect.escapechar); print "Quote Char : " + str(dialect.quotechar) + " Line Terminator : " + str(dialect.lineterminator); print
  • 14. Automatically Detecting Dialects • For data where parameters are unknown. • Sniffer class helps to understand the parameters in the data.parameters in the data. • (Lets see this later… )
  • 15. TASK • Given an array length 1 or more of ints, return the difference between the largest and smallest values in the list • Input : [10, 3, 5, 6]• Input : [10, 3, 5, 6] • Output: 7
  • 16. TASK • Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. • Input / Output : [1, 2, 2] → True• Input / Output : [1, 2, 2] → True Input / Output : [1, 2, 1, 2] → False Input / Output : [2, 1, 2] → False
  • 17. TASK • Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. • If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value.ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more. Input/Output : [1, 2, 3, 4, 100] → 3 Input/Output: [1, 1, 5, 5, 10, 8, 7] → 5